我得到了一些我无法计算的错误。知道我的示例代码出了什么问题吗?

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

当前回答

您的问题是类B没有被声明为“新型”类。这样修改:

class B(object):

它会起作用的。

Super()和所有子类/超类只适用于新样式的类。我建议你养成在任何类定义上都键入that (object)的习惯,以确保它是一个新型的类。

旧式类(也称为“经典”类)总是classobj类型;新型类的类型是type。这就是为什么你看到了错误消息:

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,所有的课程都是新式的。你仍然可以使用旧式类的语法,但是你得到了一个新式类。在python3中。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, 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(object):

它会起作用的。

Super()和所有子类/超类只适用于新样式的类。我建议你养成在任何类定义上都键入that (object)的习惯,以确保它是一个新型的类。

旧式类(也称为“经典”类)总是classobj类型;新型类的类型是type。这就是为什么你看到了错误消息:

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,所有的课程都是新式的。你仍然可以使用旧式类的语法,但是你得到了一个新式类。在python3中。X你不会有这个问题。

当我使用python 2.7时,我也面临着发布的问题。它在python 3.4中工作得非常好

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

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