Jam*_*mes 12 python recursion metaclass class
我在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
Run Code Online (Sandbox Code Playgroud)
对于我们的元类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__`
Run Code Online (Sandbox Code Playgroud)
所有这些在CPython 2.7.2,PyPy 1.6.0(实现Python 2.7.1)和Jython 2.2.1(不知道是什么Python版本)中的工作方式相同(除了更改为__metaclass__,而__next__不是特殊方法) ,如果有的话 - 我对Jython不太熟悉).
我无法找到关于__class__允许分配的条件的很多解释(显然,相关类型必须是用户定义的,并且在某种意义上具有类似的布局?).请注意,A它必须既是子类,MC也是分配__class__工作的实例.像这样的递归元类层次结构真的应该被接受吗?我很困惑.
递归元类层次实际上是语言核心的一部分:
>>> type(type)
<class 'type'>
Run Code Online (Sandbox Code Playgroud)
所以即使是标准的元类type也是它自己的类型.这个构造没有概念上的问题 - 它只是意味着__class__类的属性指向类本身.
__class__仅对用户定义的类允许对属性的分配.如果原始类和新类都没有定义__slots__,或者两者都设置__slots__为相同的序列,则赋值是合法的.