super() 失败并出现错误:TypeError“参数 1 必须是类型,而不是 classobj";当父级不继承自对象时 [英] super() fails with error: TypeError "argument 1 must be type, not classobj" when parent does not inherit from object

查看:27
本文介绍了super() 失败并出现错误:TypeError“参数 1 必须是类型,而不是 classobj";当父级不继承自对象时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了一些我无法弄清楚的错误.知道我的示例代码有什么问题吗?

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)

我从超级"内置方法的帮助下获得了示例测试代码.

I got the sample test code from help of 'super' built-in method.

这里是错误:

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 类型;新式类是 type 类型.这就是您看到错误消息的原因:

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 必须是类型,而不是 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 必须是类型,而不是 classobj";当父级不继承自对象时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆