python - super() 失败并出现错误 : TypeError "argument 1 m

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

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/

相关文章:

python - 如何使用 open with 语句打开文件

linux - 确定 Linux 二进制文件的直接共享对象依赖关系?

python - 在 Python 中写入 UTF-8 文件

python - 如何使 Jupyter Notebook 中的内联图更大?

linux - 使用 grep 搜索包含点的字符串

bash - 如何在 Bash 中比较两个点分隔版本格式的字符串?

python - 在 Python 3 中将字节转换为十六进制字符串的正确方法是什么?

python - 在 numpy.array 中查找唯一行

python - 如果我在 Python 脚本运行时修改它会发生什么?

python - 在 Linux 中安装 Pillow(Python 模块)时失败