我得到一些我无法弄清楚的错误.任何线索我的示例代码有什么问题?
class B:
def meth(self, arg):
print arg
class C(B):
def meth(self, arg):
super(C, self).meth(arg)
print C().meth(1)
Run Code Online (Sandbox Code Playgroud)
我从"超级"内置方法的帮助下得到了示例测试代码."C"级是
这是错误:
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
Run Code Online (Sandbox Code Playgroud)
仅供参考,这是来自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 …Run Code Online (Sandbox Code Playgroud) 我想在python中从键盘读取数据
我试试这个:
nb = input('Choose a number')
print ('Number%s \n' % (nb))
Run Code Online (Sandbox Code Playgroud)
但它不起作用,既不是日食也不是终端,它总是停止问题.我可以输入一个数字,但没有任何事情发生.
你知道为什么吗?
在Python 2.7和3中,我使用以下方法来调用超类的函数:
class C(B):
def __init__(self):
B.__init__(self)
Run Code Online (Sandbox Code Playgroud)
我看到也可以B.__init__(self)用super(B, self).__init__()和替换python3 super().__init__().
这样做有什么优点或缺点吗?B至少直接为我调用它更有意义,但也许有一个很好的理由super()只能在使用元类时使用(我通常会避免).
这个问题与What does 'super' do in Python? 的帖子有关。,如何初始化基(超)类?和Python:如何从超类创建子类?SuperClass它描述了从SubClassas内部初始化 a 的两种方法
class SuperClass:
def __init__(self):
return
def superMethod(self):
return
## One version of Initiation
class SubClass(SuperClass):
def __init__(self):
SuperClass.__init__(self)
def subMethod(self):
return
Run Code Online (Sandbox Code Playgroud)
或者
class SuperClass:
def __init__(self):
return
def superMethod(self):
return
## Another version of Initiation
class SubClass(SuperClass):
def __init__(self):
super(SubClass, self).__init__()
def subMethod(self):
return
Run Code Online (Sandbox Code Playgroud)
所以我对需要在
and
中显式传递self参数
感到有点困惑。(事实上,如果我打电话我会得到错误SuperClass.__init__(self)super(SubClass, self).__init__()SuperClass.__init__()
TypeError: __init__() missing 1 required positional argument: …Run Code Online (Sandbox Code Playgroud) python ×4
super ×2
superclass ×2
inheritance ×1
input ×1
keyboard ×1
object ×1
oop ×1
parent ×1
python-2.7 ×1
python-3.x ×1
self ×1
subclass ×1