2015-08-20 47 views
0

從這裏的文件,它聲稱超()方法(ARG)做同樣的事情:超(C,個體經營)。方法(ARG)。Python 3中繼承等效的語句

https://docs.python.org/3/library/functions.html#super

class shape(object): 
    def __init__(self, type): 
     self.shapeType = type 

class coloredShape1(shape): 
    def __init__(self, type, color): 
     super().__init__(type) 
     self.shapeColor = color 

class coloredShape2(shape): 
    def __init__(self, type, color): 
     super(shape, self).__init__(type) 
     self.shapeColor = color 

circle = shape("circle") 
blueRectangle = coloredShape1("rectangle", "blue") 
redSquare = coloredShape2("square", "blue") 

有與blueRectangle創作沒有任何問題,但是,redSquare線引發以下厚望:

Traceback (most recent call last): 
    File "test.py", line 17, in <module> 
    redSquare = coloredShape2("square", "blue") 
File "test.py", line 12, in __init__ 
    super(shape, self).__init__(type) 
TypeError: object.__init__() takes no parameters 

我不理解這兩者之間的區別。有人能解釋我做錯了什麼嗎?

回答

2

您通過錯誤的類到super(),所以你叫object.__init__,而不是shape.__init__

class coloredShape2(shape): 
    def __init__(self, type, color): 
     super(coloredShape2, self).__init__(type) 
     self.shapeColor = color