- mongodb - 在 MongoDB mapreduce 中,如何展平值对象?
- javascript - 对象传播与 Object.assign
- html - 输入类型 ="submit"Vs 按钮标签它们可以互换吗?
- sql - 使用 MongoDB 而不是 MS SQL Server 的优缺点
我遇到了一些我无法弄清楚的错误。任何线索我的示例代码有什么问题?
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/
我有这段代码,但我无法运行它,因为我得到了这个错误:“TypeError:'classobj' 对象不可订阅”这是我的代码: import cgi import customerlib form=cg
从另一个类方法内部使用 self.methodname() 调用类方法时出现以下错误。 TypeError: 'classobj' object is not subscriptable 可能是什么问
根据 here : The __mro__ attribute of the type lists the method resolution search order used by both ge
我在 saucelabs example.py 文件中使用 import new 模块找到了以下代码片段。 import new # .. snip .. def on_platforms(platf
作为一名 Python 新手,我构建了一个庞大且庞大的项目,虽然相当丑陋,但却满足了我的要求。但我刚刚打破了它。 我试图调用单独文件夹中保存的各种脚本,例如 execfile("folder1/scr
super() 的以下使用引发了 TypeError:为什么? >>> from HTMLParser import HTMLParser >>> class TextParser(HTMLPars
我真的希望我能在这里更具体一些,但我已经通读了相关问题,但似乎没有一个与我在这里遇到的问题有关,而且我也不了解我遇到的问题。这是一个家庭作业,所以我犹豫要不要把我所有的程序代码都贴出来,这是一个精简版
例如; 我想转变 {Aug 07, 2020: [Instance of 'ActivityLog', Instance of 'ActivityLog'], Aug 04, 2020: [Insta
这个问题已经有答案了: How to use super() when subclassing Tkinter widgets? [duplicate] (2 个回答) super() fails w
我有一个类 - A - 没有方法,只有主要方法。 在其他类(class) - B - 我需要调用那个 main.做什么最好?从使用的资源、时间和功耗以及效率来看? 从类 A 创建一个“a”对象并执行
在 Python 中,我试图在类中运行一个方法,但出现错误: Traceback (most recent call last): File "C:\Users\domenico\Desktop\
我遇到了一些我无法弄清楚的错误。任何线索我的示例代码有什么问题? class B: def meth(self, arg): print arg class C(B):
当我运行下面提供的代码时,出现以下错误: 类型错误:必须使用 Page 实例作为第一个参数调用未绑定(bind)方法 setSize()(改为使用 int 实例) In my main, I call
我是一名优秀的程序员,十分优秀!