Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to add two instances of my custom class

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)

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading