簡體   English   中英

在子類實例上調用父構造方法

[英]Calling Parent Constructor on Subclass instance

如果我沒記錯的話,在C ++中,可以在子類的實例上調用父類的構造函數,以便創建父類的實例,以便僅復制重疊的屬性。 python中是否存在這樣的功能,因此以下“ python”代碼將起到相同作用?

如果我有父母班的水果

class Fruit():
    def __init__(self, color):
        self.color = color

和一個孩子班的蘋果

class Apple(Fruit):
    def __init__(self, color, seeds):
        self.seeds = seeds
        super().__init__(color)

你可以做

an_apple = Apple('red', 42)
a_fruit = Fruit(an_apple)

並得到紅色水果。

我唯一能想到的就是制作一個Factory方法:

class Fruit():
    def __init__(self, color):
        self.color = color
    @staticmethod
    def MakeFruit(aFruit):
        return Fruit(aFruit.color)

用法:

an_apple = Apple('red', 42)  #assuming Apple as before
a_fruit = Fruit('blue')
a_red_fruit = Fruit.MakeFruit(an_apple)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM