gpt4 book ai didi

python - 没有足够的参数传递给 __init__()

转载 作者:行者123 更新时间:2023-12-01 06:13:40 27 4
gpt4 key购买 nike

下面的错误是什么?另外,有没有更好的方法来实现以下类?

     #!/usr/bin/python

class Datacenters:
def __init__(self,name,location,cpu,mem):
self.name=name
self.location=location
self.cpu=cpu
self.mem=mem

def getparam(self):
return self.name,self.location ,self.cpu,self.mem

def getname(self):
return self.name

class WS(Datacenters):
def __init__(self,name,location,cpu,mem,obj):
#datacentername = Datacenters.__init__(self) #To which data center it is associated
self.dcname =obj.name #To which data center it is associated

Datacenters.__init__(obj,name,location,cpu,mem)

def getparam(self,obj):
self.name,self.location ,self.cpu,self.mem = obj.getparam()
print self.dcname
#return self.name,self.location ,self.cpu,self.mem,obj.name

def getwsname(self):
return self.name

class Pcs(WS):
def __init__(self,name,location,cpu,mem,obj):
self.wsname = obj.getwsname() #To which WS it is associated
WS.__init__(obj,name,location,cpu,mem)

def getparam(self,obj):
print obj.getparam()
print self.wsname


a = Datacenters("dc1","Bl1",20,30)
print a.getparam()
b = WS("WS1","Bl1",21,31,a)
print b.getparam(a)
c = Pcs("PC1","Bl1",20,30,b)
#print c.getparam(b)

输出:

   Press ENTER or type command to continue 
('dc1', 'Bl1', 20, 30)
dc1
None
Traceback (most recent call last):
File "class1.py", line 45, in <module>
c = Pcs("PC1","Bl1",20,30,b)
File "class1.py", line 34, in __init__
WS.__init__(obj,name,location,cpu,mem)
TypeError: __init__() takes exactly 6 arguments (5 given)

最佳答案

错误在于您传递了五个参数,但 __init__ 需要六个参数。数一数:

def __init__(self,name,location,cpu,mem,obj):

六个参数。你可以这样调用它:

WS.__init__(obj,name,location,cpu,mem)

五个论点。第一个 self 丢失了。您应该问自己的是为什么您不必一直传递六个参数。

这是因为当您在实例上调用该方法时,self 会自动传入。但是,在这种情况下,您不会在实例上调用它,而是直接在类上调用它。这种情况当然不需要这样做,正确的语法是:

WS(obj,name,location,cpu,mem)

正如您确实在上面指出的那样,可以进一步提高。

关于python - 没有足够的参数传递给 __init__(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4482682/

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