super()失败并出现错误:TypeError"参数1必须是type,而不是classobj"当父不从对象继承时 [英] super() fails with error: TypeError "argument 1 must be type, not classobj" when parent does not inherit from object
问题描述
我得到一些我无法弄清楚的错误。我的示例代码有什么问题吗?
I get some error that I can't figure out. Any clue what is wrong with my sample code?
class B:
def meth(self, arg):
print arg
class C(B):
def meth(self, arg):
super(C, self).meth(arg)
print C().meth(1)
我从帮助中获得了示例测试代码'超'内置方法。 C类是
I got the sample test code from help of 'super' built-in method. The class "C" is the
这是错误:
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本身:
FYI, here is the help(super) from python itself:
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类未被声明为新式课程。像这样更改:
Your problem is that class B is not declared as a "new-style" class. Change it like so:
class B(object):
它会起作用。
super()
并且所有子类/超类的东西只适用于新式类。我建议你养成在任何类定义上输入(object)
的习惯,以确保它是一个新式的类。
super()
and all subclass/superclass stuff only works with new-style classes. I recommend you get in the habit of always typing that (object)
on any class definition to make sure it is a new-style class.
旧式类(也称为经典类)的类型始终为 classobj
;新式类的类型为类型
。这就是您收到错误消息的原因:
Old-style classes (also known as "classic" classes) are always of type classobj
; new-style classes are of type type
. This is why you got the error message you saw:
TypeError:super()参数1必须是type,而不是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中你不会遇到这个问题。
Note that in Python 3.x, all classes are new-style. You can still use the syntax from the old-style classes but you get a new-style class. So, in Python 3.x you won't have this problem.
这篇关于super()失败并出现错误:TypeError"参数1必须是type,而不是classobj"当父不从对象继承时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!