![](/img/trans.png)
[英]Reason for calling super class constructor using superclass.__init()__ instead of superclass()
[英]Reason for calling super class constructor from subclass?
根據Liang的Python編程介紹
class(superclass):
讓您進入超一流
super().__init__()
實例化超類,以便您可以訪問其數據字段和方法。
不過,這似乎不正確; 在下面的代碼中,我使用第一個關鍵字class(superclass)
訪問超類,但從未使用super().__ init __()對其進行初始化,但無論如何我仍然可以完全訪問所有方法。
如果僅擴展父類使我可以訪問其方法,那么調用父類的構造函數有什么意義?
參考: 使用Python編程簡介
碼:
class GeometricObject:
def __init__(self,color = "green",filled = True):
self.__color = color
self.__filled = filled
def getColor(self):
return self.__color
def setColor(self, color):
self.__color = color
def isFilled(self):
return self.__filled
def setFilled(self,filled):
self.__filled = filled
def __str__(self):
return "Color: " + self.__color + \
" and filled: " + str(self.__filled)
class square(GeometricObject):
def __init__(self,width,height):
self.__width = width
self.__height = height
def getHeight(self):
return self.__height
def getWidth(self):
return self.__width
def setHeight(self,height):
self.__height = height
def setWidth(self,width):
self.__width = width
我希望代碼不會來自Python書籍的任何介紹:這是非常糟糕的非Python語言。
但是問題的答案是,擴展使您可以訪問方法 ,但不執行超類__init__
中的任何設置。 在您的示例中, square
實例可以訪問getColor
方法,但是實際上調用它會產生錯誤,因為您從未運行過GeometricObject.__init__
來首先設置self.__color
的值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.