<p>好吧,你已经把一些概念混为一谈了!我要问你几个具体的问题。</p>
<p>一般来说,理解super、MRO和metclasses要复杂得多,因为在Python的最后几个版本中,这个棘手的领域发生了很多变化。</p>
<p><a href="http://docs.python.org/reference/datamodel.html" rel="noreferrer">Python's own documentation</a>是一个非常好的参考,并且完全是最新的。有一个<a href="http://www.ibm.com/developerworks/linux/library/l-pymeta.html" rel="noreferrer">IBM developerWorks article</a>可以作为一个介绍,它采用了一种更基于教程的方法,但是请注意,它已经有5年的历史了,并且花了很多时间讨论元类的老式方法。</p>
<p><strong><code>super</code></strong>是访问对象的超级类的方式。它比(例如)Java的<code>super</code>关键字更复杂,这主要是由于Python中的多重继承。正如<a href="http://fuhm.net/super-harmful/" rel="noreferrer">Super Considered Harmful</a>所解释的,使用<code>super()</code>可能会导致隐式地使用超级类链,其顺序由<a href="http://www.python.org/download/releases/2.3/mro/" rel="noreferrer">Method Resolution Order</a>(MRO)定义。</p>
<p>通过调用类(而不是实例)上的<code>mro()</code>,可以很容易地看到类的MRO。注意,元类不在对象的超类层次结构中。</p>
<p><a href="https://stackoverflow.com/users/17624/thomas-wouters">Thomas</a>元类的描述<a href="https://stackoverflow.com/questions/100003/what-is-a-metaclass-in-python">here</a>非常好:</p>
<blockquote>
<p>A metaclass is the class of a class.
Like a class defines how an instance
of the class behaves, a metaclass
defines how a class behaves. A class
is an instance of a metaclass.</p>
</blockquote>
<p>在您给出的示例中,下面是发生的情况:</p>
<ol>
<li><p>正在调用<code>__new__</code>
冒泡到
先生。在这种情况下,<code>super(MyType,
cls)</code>将解析为<code>type</code>;
调用<code>type.__new__</code>让Python
完成这是正常情况
创建步骤。</p></li>
<li><p>这个例子使用的是元类
强制执行一个单子。他是
重写中的<code>__call__</code>
元类,以便每当类
实例被创建,他拦截
可以绕过实例
如果已经有一个
(存储在<code>cls.instance</code>中)。注意
在
元类不够好,
因为只有在
创建<em>类</em>。超越
<code>__new__</code>在类上可以工作,
然而。</p></li>
<li><p>这显示了一种动态地
创建类。他来了
附加提供的类的名称
到创建的类名,以及
将其添加到类层次结构中
我也是。</p></li>
</ol>
<p>我不确定您要查找的是哪种类型的代码示例,但这里有一个简短的示例,显示了元类、继承和方法解析:</p>
<pre><code>class MyMeta(type):
def __new__(cls, name, bases, dct):
print "meta: creating %s %s" % (name, bases)
return type.__new__(cls, name, bases, dct)
def meta_meth(cls):
print "MyMeta.meta_meth"
__repr__ = lambda c: c.__name__
class A(object):
__metaclass__ = MyMeta
def __init__(self):
super(A, self).__init__()
print "A init"
def meth(self):
print "A.meth"
class B(object):
__metaclass__ = MyMeta
def __init__(self):
super(B, self).__init__()
print "B init"
def meth(self):
print "B.meth"
class C(A, B):
__metaclass__ = MyMeta
def __init__(self):
super(C, self).__init__()
print "C init"
>>> c_obj = C()
meta: creating A (<type 'object'>,)
meta: creating B (<type 'object'>,)
meta: creating C (A, B)
B init
A init
C init
>>> c_obj.meth()
A.meth
>>> C.meta_meth()
MyMeta.meta_meth
>>> c_obj.meta_meth()
Traceback (most recent call last):
File "mro.py", line 38, in <module>
c_obj.meta_meth()
AttributeError: 'C' object has no attribute 'meta_meth'
</code></pre>