簡體   English   中英

通過子實例訪問父類方法

[英]Access parent class method through child instance

我有以下代碼:

class Organ():
    def __init__(self, organ_name, organ_weight):
        self.organ_name = organ_name
        self.organ_weight = organ_weight
    
    def __repr__(self):
        return "The {organ}'s weight is {weight}"\
        .format(organ=self.organ_name, weight = self.organ_weight) 

class Heart(Organ):
    def __init__(self, heart_weight):
        self.heart_weight_grams = heart_weight
        super().__init__(__class__.__name__, self.heart_weight_grams)
    
    def __repr__(self):
        return "My heart's weight is {weight} grams"\
        .format(weight=self.heart_weight_grams)

my_heart = Heart(200)
print(my_heart) #returns "My heart's weight is 200 grams"

從我的子實例my_heart ,如何訪問父類方法__repr__()方法?

要從孩子訪問父級使用super() ,即: super().__repr__()但在這里你不需要它,實際上你可能使用heart_weight_grams屬性,因為它與父organ_weight中的organ_weight相同

如果你有更多的屬性進入Heart類,你可以調用__repr__ parent 並從 child 類中連接更多信息

class Organ:
    def __init__(self, organ_name, organ_weight):
        self.organ_name = organ_name
        self.organ_weight = organ_weight

    def __repr__(self):
        return "The {organ}'s weight is {weight}".format(organ=self.organ_name, weight=self.organ_weight)
        # return f"The {self.organ_name}'s weight is {self.organ_weight}" # shorter 
    
class Heart(Organ):
    def __init__(self, heart_weight, hearbeat=60):
        super(Heart, self).__init__("heart", heart_weight)
        self.hearbeat = hearbeat

    def __repr__(self):
        return super().__repr__() + f" and beats at {self.hearbeat}"

my_heart = Heart(200)
print(my_heart)  # The Heart's weight is 200

當您繼承一個類時,您可以使用super訪問父函數。 只需使用super().__repr__()來訪問該函數。

暫無
暫無

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

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