How to iterate over class attributes?
I'm looking for a way to not repeat myself in lines 10 to 14. This is always the same code and my real code is more complex. What can I do about this?
01 class MyValues:
02 def __init__(self, a, b, c, d, e):
03 self.a = a
04 self.b = b
05 self.c = c
06 self.d = d
07 self.e = e
08
09 def add_number(values: MyValues, number_to_add):
10 values.a += number_to_add
11 values.b += number_to_add
12 values.c += number_to_add
13 values.d += number_to_add
14 values.e += number_to_add
15 return values
Solution 1:
This would work if all your attributes need to be added:
class MyValues:
def __init__(self, a, b, c, d, e):
self.a = a
self.b = b
self.c = c
self.d = d
self.e = e
# should name the first arg to be self
def add_number(self, number_to_add):
for k in self.__dict__:
setattr(self, k, getattr(self, k) + number_to_add)
return self
But like @Barmar said you should consider to add them as a list or dict in the first place