关于python:没有足够的参数传递给 __init__ ()

not enough arguments passed to __init__()

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
     #!/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)

输出:

1
2
3
4
5
6
7
8
9
10
   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)


错误是你传递了5个参数,但是__init__需要6个。数一数:

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

六个论点。你这样称呼它:

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

五个论点。第一个,self丢失了。你应该问自己的是,为什么你不必总是通过六个论点。

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

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

正如你上面所说的,注释更进一步。