'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 1:[1]
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
Solution 2:[2]
You could define the __add__ function to leverage the + operator
class Values:
def __init__(self,x,y):
self.x = x
self.y = y
def __add__(self, other):
return Values(self.x + other.x, self.y + other.y)
then for example
>>> c1 = Values(5,6)
>>> c2 = Values(7,9)
>>> c3 = c1 + c2
>>> c3.x
12
>>> c3.y
15
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | BrokenBenchmark |
| Solution 2 | Cory Kramer |
