我在 realpython.com 中找到了關于 python super() 的代碼,如果兩個類都沒有父類(不繼承),我不明白 Rectangle 和 Triangle init方法中 super() 的目的是什么。
class Rectangle:
def __init__(self, length, width, **kwargs):
self.length = length
self.width = width
super().__init__(**kwargs)
def area(self):
return self.length * self.width
class Square(Rectangle):
def __init__(self, length, **kwargs):
super().__init__(length=length, width=length, **kwargs)
class Triangle:
def __init__(self, base, height, **kwargs):
self.base = base
self.height = height
super().__init__(**kwargs)
def tri_area(self):
return 0.5 * self.base * self.height
class RightPyramid(Square, Triangle):
...
uj5u.com熱心網友回復:
這樣,這些類可以使用多重繼承,并且它們可能在編碼時得到未知的祖先 - 呼叫super,傳遞它們可能獲得的任何未知引數,確保它們在以這種方式使用時會很好地發揮作用。
例如,假設這些形狀用于表示創建具體的 3D 列印塑料物件。
class Print3D:
def __init__(self, *, filament="PLA", **kw):
self.filament=filament
print("Print3D part initialized")
super().__init__(**kwargs)
現在可以做到:
class PrintedSquare(Square, Print3D):
pass
mysquare = PrintedSquare(length=20, filament="PVC")
一切都會正常進行。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/537509.html
標籤:python-3.x遗产
