新聞中心
小編給大家分享一下Python中元類指的是什么,相信大部分人都還不怎么了解,因此分享這篇文章給大家參考一下,希望大家閱讀完這篇文章后大有收獲,下面讓我們一起去了解一下吧!

Python2創(chuàng)建類的時(shí)候,可以添加一個(gè)__metaclass__屬性:
class Foo(object):
__metaclass__ = something...
[...]
如果你這樣做,Python會(huì)使用元類來創(chuàng)建Foo這個(gè)類。Python會(huì)在類定義中尋找__metaclass__。如果找到它,Python會(huì)用它來創(chuàng)建對(duì)象類Foo。如果沒有找到它,Python將使用type來創(chuàng)建這個(gè)類。
在Python3中語法改變了一下:
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中元類指的是什么的所有內(nèi)容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內(nèi)容對(duì)大家有所幫助,如果還想學(xué)習(xí)更多知識(shí),歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道!
分享標(biāo)題:Python中元類指的是什么-創(chuàng)新互聯(lián)
文章網(wǎng)址:http://fisionsoft.com.cn/article/gsece.html


咨詢
建站咨詢
