Home > Software design >  How to add two instances of my custom class
How to add two instances of my custom class

Time:11-30

I want to run this code (must) including the attribute value next to total in the print section. What code should I insert inside the class to do it?

class Random:
    def __init__(self, x):
        self.x = x

    def __add__(self, other):
        return self.x   other.x


p1 = Random(2)
p2 = Random(3)

total = p1   p2

print(total.value)

CodePudding user response:

Return an instance of Random in your __add__ method and add a property with the name value for the class.

class Random:
    def __init__(self, x):
        self.x = x

    def __add__(self, other):
        return Random(self.x   other.x)

    @property
    def value(self):
        return self.x


p1 = Random(2)
p2 = Random(3)

total = p1   p2

print(total.value)

Of course the better option would be to replace the instance attribute x with value. Then there's no need for the property.

class Random:
    def __init__(self, x):
        self.value = x

    def __add__(self, other):
        return Random(self.value   other.value)

CodePudding user response:

Make total a Random as well.

class Random:
    def __init__(self, value):
        self.value = value

    def __add__(self, other):
        return Random(self.value   other.value)


p1: Random = Random(2)
p2: Random  = Random(3)

total: Random = p1   p2

print(total.value)
  • Related