在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 aTypeError: super() argument 1 must be type, not classobj如果我更換class X用class X(object),它會奏效。這有什么解釋?
3 回答

慕尼黑的夜晚無繁華
TA貢獻1864條經驗 獲得超6個贊
原因是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

RISEBY
TA貢獻1856條經驗 獲得超5個贊
另外,除非必須,否則不要使用super()。您可能會懷疑,使用新型類不是通用的“正確的事情”。
有時,您可能期望多重繼承,并且可能會想要多重繼承,但是在您知道MRO的繁瑣細節之前,最好不要去管它,并堅持:
X.a(self)
添加回答
舉報
0/150
提交
取消