super()失败并出现错误:当父不从对象继承时,TypeError“参数1必须是type,而不是classobj”

时间:2009-11-11 04:36:05

标签: python object inheritance parent super

我得到一些我无法弄清楚的错误。我的示例代码有什么问题吗?

class B:
    def meth(self, arg):
        print arg

class C(B):
    def meth(self, arg):
        super(C, self).meth(arg)

print C().meth(1)

我从'super'内置方法的帮助下得到了示例测试代码。 类是

这是错误:

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)
 |

4 个答案:

答案 0 :(得分:287)

您的问题是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中你不会遇到这个问题。

答案 1 :(得分:126)

此外,如果您无法更改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)

答案 2 :(得分:15)

如果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)

答案 3 :(得分:3)

当我使用python 2.7时,我也遇到过发布的问题。它与python 3.4一起工作得很好

为了使它在python 2.7中工作,我在程序的顶部添加了__metaclass__ = type属性并且它有效。

__metaclass__:它简化了旧式类和新式类的转换。