下面的错误是什么?另外,有没有更好的方法来实现以下类?
#!/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)
答案 0 :(得分:2)
错误是您传递了五个参数,但__init__
需要六个参数。算上他们:
def __init__(self,name,location,cpu,mem,obj):
六个论点。你这样称呼它:
WS.__init__(obj,name,location,cpu,mem)
五个论点。第一个,self
丢失了。您应该问自己的原因是为什么您不必一直传递六个参数。
这是因为当您在实例上调用方法时会自动传入self
。但是,在这种情况下,您不会在实例上调用它,而是直接在类上调用它。在这种情况下当然没有必要这样做,正确的语法是:
WS(obj,name,location,cpu,mem)
正如你上面确实注意到的那样。