相关疑难解决方法(0)

super()失败并出现错误:当父不从对象继承时,TypeError"参数1必须是type,而不是classobj"

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

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 inheritance object parent super

186
推荐指数
4
解决办法
11万
查看次数

如何阅读键盘输入?

我想在python中从键盘读取数据

我试试这个:

nb = input('Choose a number')
print ('Number%s \n' % (nb))
Run Code Online (Sandbox Code Playgroud)

但它不起作用,既不是日食也不是终端,它总是停止问题.我可以输入一个数字,但没有任何事情发生.

你知道为什么吗?

python keyboard input

118
推荐指数
3
解决办法
44万
查看次数

super()和直接调用超类之间的区别

在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()只能在使用元类时使用(我通常会避免).

python oop superclass python-2.7 python-3.x

28
推荐指数
1
解决办法
6070
查看次数

在 python 中调用超类的 __init__ 时显式传递 Self

这个问题与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 subclass self super superclass

9
推荐指数
3
解决办法
1万
查看次数