Python super() 引发 TypeError [英] Python super() raises TypeError
本文介绍了Python super() 引发 TypeError的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在 Python 2.5 中,以下代码引发 TypeError
:
如果我将 class X
替换为 class X(object)
,它将起作用.对此有何解释?
解决方案
原因是 super()
仅作用于 新式类,在2.x系列中的意思是从object
扩展而来:
In Python 2.5, the following code raises a 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
If I replace the class X
with class X(object)
, it will work. What's the explanation for this?
解决方案
The reason is that super()
only operates on new-style classes, which in the 2.x series means extending from 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
这篇关于Python super() 引发 TypeError的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文