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 :
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