![](/img/trans.png)
[英]super() raises “TypeError: must be type, not classobj” for new-style class
[英]super() fails with error: TypeError "argument 1 must be type, not classobj" when parent does not inherit from object
我收到一些我无法弄清楚的错误。 任何线索我的示例代码有什么问题?
class B:
def meth(self, arg):
print arg
class C(B):
def meth(self, arg):
super(C, self).meth(arg)
print C().meth(1)
我从“超级”内置方法的帮助中获得了示例测试代码。
这是错误:
Traceback (most recent call last):
File "./test.py", line 10, in ?
print C().meth(1)
File "./test.py", line 8, in meth
super(C, self).meth(arg)
TypeError: super() argument 1 must be type, not classobj
仅供参考,这是python本身的帮助(超级):
Help on class super in module __builtin__:
class super(object)
| super(type) -> unbound super object
| super(type, obj) -> bound super object; requires isinstance(obj, type)
| super(type, type2) -> bound super object; requires issubclass(type2, type)
| Typical use to call a cooperative superclass method:
| class C(B):
| def meth(self, arg):
| super(C, self).meth(arg)
|
您的问题是 B 类未声明为“新型”类。 像这样改变它:
class B(object):
它会起作用。
super()
和所有子类/超类的东西只适用于新式类。 我建议您养成始终在任何类定义上键入该(object)
的习惯,以确保它是一个新型类。
旧式类(也称为“经典”类)始终是classobj
类型; 新式类的类型为type
。 这就是您看到错误消息的原因:
TypeError: super() argument 1 must be type, not classobj
试试这个,看看你自己:
class OldStyle:
pass
class NewStyle(object):
pass
print type(OldStyle) # prints: <type 'classobj'>
print type(NewStyle) # prints <type 'type'>
请注意,在 Python 3.x 中,所有类都是新样式的。 您仍然可以使用旧式类的语法,但您会得到一个新式类。 所以,在 Python 3.x 中你不会有这个问题。
此外,如果您无法更改 B 类,则可以使用多重继承来修复错误。
class B:
def meth(self, arg):
print arg
class C(B, object):
def meth(self, arg):
super(C, self).meth(arg)
print C().meth(1)
如果python版本是3.X就可以了。
我认为您的python版本是2.X,添加此代码时超级会起作用
__metaclass__ = type
所以代码是
__metaclass__ = type
class B:
def meth(self, arg):
print arg
class C(B):
def meth(self, arg):
super(C, self).meth(arg)
print C().meth(1)
当我使用 python 2.7 时,我也遇到了发布的问题。 它在 python 3.4 上工作得很好
为了让它在 python 2.7 中工作,我在我的程序顶部添加了__metaclass__ = type
属性并且它起作用了。
__metaclass__
:它简化了旧式类和新式类的转换。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.