Skip to main content
 首页 » 编程设计

python之如何使用 super 命令python

2025年05月04日34lhb25

我在使用 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