Geo*_*Geo 107 python inheritance python-2.x super
在Python 2.5中,以下代码引发了TypeError:
>>> class X:
def a(self):
print "a"
>>> class Y(X):
def a(self):
super(Y,self).a()
print "b"
>>> c = Y()
>>> c.a()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 3, in a
TypeError: super() argument 1 must be type, not classobj
Run Code Online (Sandbox Code Playgroud)
如果我更换class X用class X(object),它会奏效.对此有何解释?
Cod*_*ous 130
原因是super()只对新式的类进行操作,在2.x系列中,它意味着从object以下方面扩展:
>>> class X(object):
def a(self):
print 'a'
>>> class Y(X):
def a(self):
super(Y, self).a()
print 'b'
>>> c = Y()
>>> c.a()
a
b
Run Code Online (Sandbox Code Playgroud)
bob*_*nce 14
另外,除非必须,否则不要使用super().对于您可能怀疑的新式课程,这不是通用的"正确的事情".
有些时候你期待多重继承并且你可能想要它,但是在你知道MRO的毛茸茸细节之前,最好不要管它并坚持:
X.a(self)
Run Code Online (Sandbox Code Playgroud)