how to use super().__add__ in a derived class

Viewed 164

My code works but I'm not sure if this the correct way to implement it. I'm trying to use the base class "add" method in the derived class. super().__add__ returns a base class therefore I must somehow "convert" the class back to the derived type before returning it. Can you please take a look and tell me if there is a better/ nicer way to implement this?

class a:
def __init__(self, x, y):
    self.x = x
    self.y = y

def __repr__(self):
    return f"{self.x} {self.y}"

def __add__(self, other):
    return a(self.x + other.x, self.y + other.y)



class b(a):
    def __init__(self, x, y, z):
        super().__init__(x, y)
        self.z = z

    def __repr__(self):
        str = super().__repr__()
        return str + f" {self.z}"

    def __add__(self, other):
        temp = super().__add__(other)
        new_z = self.z + other.z
        return b(temp.x, temp.y, new_z)

Thanks! LI

1 Answers

You can make the constructor of class b compatible with that of the base class by making the additional parameter z optional with a default value:

class b(a):
    def __init__(self, x, y, z=0):
        super().__init__(x, y)
        self.z = z

so that the __add__ method of the base class can instantiate a new object by the type of the self object rather than a hard-coded class:

class a:
    def __add__(self, other):
        return type(self)(self.x + other.x, self.y + other.y)

and that the __add__ method of the derived class can modify the object returned by the __add__ method of the base class directly before returning it:

def __add__(self, other):
    temp = super().__add__(other)
    temp.z = self.z + other.z
    return temp

Demo: https://replit.com/@blhsing/UnusedDraftyPortablesoftware

Related