gpt4 book ai didi

python - super() 失败并出现错误 : TypeError "argument 1 must be type, not classobj" when parent does not inherit from object

转载 作者:IT老高 更新时间:2023-10-28 12:21:43 56 4
gpt4 key购买 nike

我遇到了一些我无法弄清楚的错误。任何线索我的示例代码有什么问题?

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

最佳答案

您的问题是 B 类未声明为“新型”类。改成这样:

class B(object):

它会起作用的。

super() 和所有子类/父类(super class)的东西只适用于新式类。我建议您养成在任何类定义中始终键入 (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 中你不会有这个问题。

关于python - super() 失败并出现错误 : TypeError "argument 1 must be type, not classobj" when parent does not inherit from object,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1713038/

56 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com