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

Adding Objects with multiple attributes

I’m trying to figure out if there’s a better way to get the same outcome from this line of code. For instance: defining a new object (c3) inside of the add_coordinates function if possible? Or is this the simplest and most effective way to add the two objects.

class Values:
    def __init__(self,x,y):
        self.x=x
        self.y=y
    def add_values(self,x,y):
        self.x=x+self.x
        self.y=y+self.y
       
c1 = Values(5,6)
c2 = Values(7,9)
c3= Values(0,0)


c3.add_values(c1.x,c1.y)
c3.add_values(c2.x,c2.y)

print(c3.x)
print(c3.y)

>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

One improvement would be to override the __iadd__ dunder method so that you can use +=, rather than using a custom function that does essentially the same thing:

class Values:
    def __init__(self,x,y):
        self.x=x
        self.y=y
        
    def __iadd__(self, other):
        return Values(self.x + other.x, self.y + other.y)

c1 = Values(5,6)
c2 = Values(7,9)
c3= Values(0,0)


c3 += c1
c3 += c2

print(c3.x)
print(c3.y)

This prints:

12
15
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