gpt4 book ai didi

python - 如何使用 super 命令python

转载 作者:太空宇宙 更新时间:2023-11-04 05:44:41 25 4
gpt4 key购买 nike

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com