![](/img/trans.png)
[英]python: calling super().__init__ too early in the __init__ method?
[英]calling super init method without arguments
我對super().__init__()
方法有疑問。 根據 W3SCHOOLS 的定義和用法(超級)是:
super()
function 用於訪問父級或兄弟級 class 的方法和屬性。
super()
function 返回代表父 class 的 object。
但是我真的不明白為什么以及在哪里可以使用super().__init__()
方法而在__init__
中沒有任何參數(因為,即使沒有super
,只要我們插入名稱,就會調用父 class 的__init__
方法括號上的父母的 class )。
我是面向對象編程的新手,所以我只是想了解它是如何工作的!!!
為了幫助您理解我的問題,請參見下面的示例:
class Rectangle:
def __init__(self, length, width):
self.length = length
self.width = width
def area1(self):
return self.length * self.width
class Square(Rectangle):
def __init__(self, length):
super().__init__(length, length)
square = Square(4)
square.area()
這里我們使用它是因為我們需要在 Rectangle class 上定義self.length, self.width
self.width
(我們插入長度,長度)。
但是我不知道為什么我們在沒有任何 arguments 的情況下使用它,就像在下一個示例中一樣。
因為我知道我們可以訪問父 class 的方法和屬性,而無需調用超級。
class Example(QMainWindow):
def __init__(self):
super().__init__()
self.lineEntry = QLineEdit(self)
self.lineEntry.move(16,16)
self.lineEntry.resize(200,40)
self.setGeometry(50,50,320,200)
self.setWindowTitle("QLineEdit Example")
self.show()
app = QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())
並非每個屬性都傳遞給構造函數 - 有些可能是在構造函數中分配了默認值的私有屬性。 此外,父類的構造函數可能會做一些事情,而不僅僅是分配屬性,例如設置緩存。 沒有super().__init__()
,它們將無法運行。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.