简体   繁体   中英

Access parent class method through child instance

I have the following code:

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"

From my child instance my_heart , how do I access the parent class method __repr__() method?

To access the parent from child use super() , ie : super().__repr__() but here you don't need it, in fact you may not use heart_weight_grams attribut, because it's the same as organ_weight in the parent

If you have more attributs into Heart class, you can call __repr__ parent and concat more info from the child class

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

When you inherit a class, you can access parent functions using super . Just use super().__repr__() to access the function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM