我犯了一些我无法理解的错误.我的示例代码有什么问题吗?

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

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()和所有子类/超类的东西只适用于新样式的类.我建议您养成在任何类定义上都键入(object)的习惯,以确保它是一个新型类.

老式课程(也被称为"classic "课程)总是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中.你不会有这个问题.

Python相关问答推荐

从收件箱获取特定列中的重复行

脚注在Python中使用regex导致错误匹配

为什么基于条件的过滤会导致pandas中的空数据框架?

从管道将Python应用程序部署到Azure Web应用程序,不包括需求包

仅从风格中获取 colored颜色 循环

使用numpy提取数据块

将整组数组拆分为最小值与最大值之和的子数组

当使用keras.utils.Image_dataset_from_directory仅加载测试数据集时,结果不同

Django mysql图标不适用于小 case

Pandas 都是(),但有一个门槛

使用groupby Pandas的一些操作

修复mypy错误-赋值中的类型不兼容(表达式具有类型xxx,变量具有类型yyy)

我想一列Panadas的Rashrame,这是一个URL,我保存为CSV,可以直接点击

cv2.matchTemplate函数匹配失败

为什么Django管理页面和我的页面的其他CSS文件和图片都找不到?'

Pandas GroupBy可以分成两个盒子吗?

matplotlib图中的复杂箭头形状

在matplotlib中使用不同大小的标记顶部添加批注

在Google Drive中获取特定文件夹内的FolderID和文件夹名称

pandas:在操作pandora之后将pandora列转换为int