2012-05-31 88 views
8

下面的代碼是給我一個錯誤出於某種原因,有人能告訴我會是什麼問題..Python類 - 超級變量

基本上,我創建了2 Point類& Circle..THe圓圈試圖繼承Point類。

Code: 


class Point(): 

    x = 0.0 
    y = 0.0 

    def __init__(self, x, y): 
     self.x = x 
     self.y = y 
     print("Point constructor") 

    def ToString(self): 
     return "{X:" + str(self.x) + ",Y:" + str(self.y) + "}" 

class Circle(Point): 
    radius = 0.0 

    def __init__(self, x, y, radius): 
     super(Point,self).__init__(x,y) 
     self.radius = radius 
     print("Circle constructor") 

    def ToString(self): 
     return super().ToString() + \ 
       ",{RADIUS=" + str(self.radius) + "}" 


if __name__=='__main__': 
     newpoint = Point(10,20) 
     newcircle = Circle(10,20,0) 

錯誤:

C:\Python27>python Point.py 
Point constructor 
Traceback (most recent call last): 
    File "Point.py", line 29, in <module> 
    newcircle = Circle(10,20,0) 
    File "Point.py", line 18, in __init__ 
    super().__init__(x,y) 
TypeError: super() takes at least 1 argument (0 given) 
+0

你做一些編輯源?你最初的'init'調用看起來像那樣嗎? –

+4

'ToString',哦!我的(pythonic)眼睛在流血 – juliomalegria

回答

13

它看起來像你已經可以有固定的原來的錯誤,這是由super().__init__(x,y)作爲錯誤信息表明造成的,雖然你修復稍不正確,而不是super(Point, self)Circle班級您應該使用super(Circle, self)

注意這裏是調用super()錯誤,CircleToString()方法的其他地方內:

 return super().ToString() + \ 
       ",{RADIUS=" + str(self.radius) + "}" 

這是Python的3個有效編碼,但是關於Python 2 super()需要參數,改寫這個作爲以下:

 return super(Circle, self).ToString() + \ 
       ",{RADIUS=" + str(self.radius) + "}" 

我也建議擺脫續行,見Maximum Line Length section of PEP 8固定此推薦的方式。

+0

錯誤消息明確指出錯誤是* not *來自該行。 –

+0

@MarkRansom - 對!謝謝。 –

+0

你應該建議'的ToString()'是不是(全部)正確的認爲做,這就是'__str__'是。 – juliomalegria

7

super(..)只需新式的類。要修復它,請從object擴展Point類。就像這樣:

class Point(object): 

而且使用超(..)的正確的方法是這樣的:

super(Circle,self).__init__(x,y) 
0
class Point(object): 

x = 0.0 
y = 0.0 

def __init__(self, x, y): 
    self.x = x 
    self.y = y 
    print("Point constructor") 

def ToString(self): 
    return "{X:" + str(self.x) + ",Y:" + str(self.y) + "}" 

class Circle(Point,object): 
radius = 0.0 

def __init__(self, x, y, radius): 
    super(Circle,self).__init__(x,y) 
    self.radius = radius 
    print("Circle constructor") 

def ToString(self): 
    return super(Circle, self).ToString() + \ 
      ",{RADIUS=" + str(self.radius) + "}" 


if __name__=='__main__':  
    newpoint = Point(10,20)  
    newcircle = Circle(10,20,0)