super()失败,错误为:当父项不从obj继承时,type error“参数1必须是type,而不是classobj”

2024-04-28 08:38:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我有个我搞不懂的错误。我的示例代码有什么问题吗?

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本身的帮助(super):

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

Tags: intestself示例objectdeftype错误
3条回答

您的问题是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'>

注意,在Python3.x中,所有类都是新样式的。您仍然可以使用旧样式类中的语法,但会得到一个新样式类。所以,在Python3.x中不会有这个问题。

如果python版本是3.X,那就没问题了。

我认为您的python版本是2.X,添加这段代码时super会起作用

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

另外,如果不能更改类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)

相关问题 更多 >