python - 如何使用 super 命令python

标签 python super

我在使用 super 命令时遇到问题

class s:
    def __init__(self,a):
        self.a=a

    def show(self):
        print self.a


class t:
    def __init__(self,b):
        self.b=b

    def show2(self):
        print self.b


class w(s):
    def __init__(self,a,b,c):
        super(w,self).__init__()
        self.b=b
        self.c=c

    def show3(self):
        super(w,self).show()
        print self.b
        print self.c

每当我创建一个对象时,它都会给出以下错误

x=w(1,2,3)

Traceback (most recent call last):
    File "<pyshell#0>", line 1, in <module>
x=w(1,2,3)
File "C:\Users\GURSAHEJ\Desktop\k.py", line 13, in __init__
super(w,self).__init__()
TypeError: must be type, not classobj

最佳答案

super function将返回一个代理对象,该代理对象将方法调用委托(delegate)给类型的父类或兄弟类,因此当你想使用它时,你需要将父名称传递给它,因为这里你的 w 类继承自 s 你可能想将 s 传递给 super:

class w(s):
    def __init__(self,a,b,c):
        super(s,self).__init__()
        self.b=b
        self.c=c

另外不要忘记传递 object给你的父类让它成为new style class :

class s(object):
        def __init__(self,a):
            self.a=a
        def show(self):
            print self.a

在 python 文档中阅读新样式和经典类 https://docs.python.org/2/reference/datamodel.html#new-style-and-classic-classes

关于python - 如何使用 super 命令python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32732503/

相关文章:

python - Mechanize 和 Python 没有正确处理 cookie

python - 简单的函数调用在 Robot Framework 中不起作用

python - 为什么 super().__init__ 没有自引用?

PyCharm 中的 python3 super() 新样式自动完成

python 3.6 : Either I miss something either generic typing breaks super chaining for inheritance

javascript - 了解 Javascript super 方法模拟代码

python - 使用 Python 在终端中生成音频铃

javascript - 使用从 Django 中的某个 URL 获取的附加文件预填写表单

python - 循环更新现有 Excel 模板

java - 为什么 addMouseListener 方法不需要 super ?