新聞中心
作為一個的程序單元,學習編程的人應該都需要掌握。今天小編為大家?guī)碓惖闹v解。

Python2創(chuàng)建類的時候,可以添加一個__metaclass__屬性:
class Foo(object):
__metaclass__ = something...
[...]
如果你這樣做,Python會使用元類來創(chuàng)建Foo這個類。Python會在類定義中尋找__metaclass__。如果找到它,Python會用它來創(chuàng)建對象類Foo。如果沒有找到它,Python將使用type來創(chuàng)建這個類。
在Python3中語法改變了一下:
class Simple1(object, metaclass=something...):
[...]
本質上是一樣的。拿一個元類例子分享一下:
class HelloMeta(type):
def __new__(cls, name, bases, attrs):
def __init__(cls, func):
cls.func = func
def hello(cls):
print 'hello world'
t = type.__new__(cls, name, bases, attrs)
t.__init__ = __init__
t.hello = hello
return t
class New_Hello(object):
__metaclass__ = HelloMeta
New_Hello初始化需要添加一個參數(shù),并包含一個叫做hello的方法:
In : h = New_Hello(lambda x: x)
In : h.func(10), h.hello()
hello world
Out: (10, None)
PS: 這個例子只能運行于Python2。
以上就是Python中元類的詳解。更多Python學習推薦:PyThon學習網教學中心。
文章名稱:創(chuàng)新互聯(lián)Python教程:Python中的元類是什么?如何快速掌握?
當前路徑:http://m.5511xx.com/article/cccseed.html


咨詢
建站咨詢
