[英]Python - an object can be its own type?
我在CPython 3.2.2中玩過元類,我發現有可能最終得到一個類型為自己的類:
Python 3.2.2 (default, Sep 5 2011, 21:17:14)
[GCC 4.6.1] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> class MC(type): #a boring metaclass that works the same as type
... pass
...
>>> class A(MC, metaclass=MC): #A is now both a subclass and an instance of MC...
... pass
...
>>> A.__class__ = A #...and now A is an instance of itself?
>>> A is type(A)
True
對於我們的元類A
,類和實例屬性之間似乎沒有太大的區別:
>>> A.__next__ = lambda self: 1
>>> next(A)
1 #special method lookup works correctly
>>> A.__dict__
dict_proxy({'__module__': '__main__',
'__next__': <function <lambda> at 0x17c9628>,
'__doc__': None})
>>> type(A).__dict__
dict_proxy({'__module__': '__main__',
'__next__': <function <lambda> at 0x17c9628>,
'__doc__': None}) #they have the same `__dict__`
所有這一切的工作原理相同(除將到__metaclass__
,並且__next__
不是一個特殊的方法)在CPython的2.7.2,1.6.0 PyPy(實現的Python 2.7.1),和Jython 2.2.1(不知道什么Python版本也就是說,如果有的話 - 我對Jython不太熟悉)。
我無法找到關於允許分配__class__
的條件的很多解釋(顯然,相關類型必須是用戶定義的,並且在某種意義上具有類似的布局?)。 請注意, A
必須同時是MC
的子類和MC
實例才能使__class__
工作。 像這樣的遞歸元類層次結構真的應該被接受嗎? 我很困惑。
遞歸元類層次實際上是語言核心的一部分:
>>> type(type)
<class 'type'>
所以即使是標准元type
也是它自己的類型。 這個構造沒有概念上的問題 - 它只是意味着類的__class__
屬性指向類本身。
僅對用戶定義的類允許對__class__
屬性進行分配。 如果原始類和新類都沒有定義__slots__
,或者兩者都將__slots__
設置為相同的序列,則賦值是合法的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.