简体   繁体   中英

How to supplement __repr__() of parent class in subclass to output additional subclass features

Lets say I have parent class A and child class B like this:

class A:
    def __init__(self,name):
        self.name = name
        
    def __repr__(self):
        return f"My name is: {self.name}"

class B(A):
    def __init__(self,name,surname):
        super(B,self).__init__(name)
        self.name = name
        self.surname = surname
    
    def __repr__(self):
        return f"My name is: {self.name} {self.surname}"
    
a = A("Jhon")
b = B("Bon","Boby")


print(a)
print(b)

Is there any way to modify the B.__repr__() without repeating code from parent class and use A.__repr__() to just append the surname to its value?

Solution that seems to work is to call super(B,self).__repr__() within B's __repr__() like this:

class A:
    def __init__(self,name):
        self.name = name
        
    def __repr__(self):
        return f"My name is: {self.name}"

class B(A):
    def __init__(self,name,surname):
        super(B,self).__init__(name)
        self.name = name
        self.surname = surname
    
    def __repr__(self):
        s = super(B,self).__repr__()
        s += f" {self.surname}"
        return s
    
a = A("Jhon")
b = B("Bon","Boby")


print(a)
print(b)

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