新聞中心
作為一個(gè)的程序單元,學(xué)習(xí)編程的人應(yīng)該都需要掌握。今天小編為大家?guī)?lái)元類的講解。

Python2創(chuàng)建類的時(shí)候,可以添加一個(gè)__metaclass__屬性:
class Foo(object):
__metaclass__ = something...
[...]
如果你這樣做,Python會(huì)使用元類來(lái)創(chuàng)建Foo這個(gè)類。Python會(huì)在類定義中尋找__metaclass__。如果找到它,Python會(huì)用它來(lái)創(chuàng)建對(duì)象類Foo。如果沒(méi)有找到它,Python將使用type來(lái)創(chuàng)建這個(gè)類。
在Python3中語(yǔ)法改變了一下:
class Simple1(object, metaclass=something...):
[...]
本質(zhì)上是一樣的。拿一個(gè)元類例子分享一下:
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初始化需要添加一個(gè)參數(shù),并包含一個(gè)叫做hello的方法:
In : h = New_Hello(lambda x: x)
In : h.func(10), h.hello()
hello world
Out: (10, None)
PS: 這個(gè)例子只能運(yùn)行于Python2。
以上就是Python中元類的詳解。更多Python學(xué)習(xí)推薦:PyThon學(xué)習(xí)網(wǎng)教學(xué)中心。
文章標(biāo)題:創(chuàng)新互聯(lián)Python教程:Python中的元類是什么?如何快速掌握?
文章出自:http://m.5511xx.com/article/cccseed.html


咨詢
建站咨詢
