Home > Software engineering >  How to iterate over class attributes?
How to iterate over class attributes?

Time:01-22

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

CodePudding user response:

you could use dictionaries like this:

01 class MyValues:
02     def __init__(self, a, b, c, d, e):
03         self.vals = {"a":a,"b":b,"c":c,"d":d,"e":e}
04    
05     def add_number(self,values: MyValues, number_to_add):
06         for value in values.vals:
07             values.vals[value] =number_to_add
08         return values

CodePudding user response:

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

CodePudding user response:

You could store your values in an array. Looping over all the values then becomes relatively simple. Plus, you won't have to manually add each value to the class.

class MyValues:
    def __init__(self, value_array ):
        self.values = value_array
        self.num_of_values = len(self.values)
    
    def add_number(self, number_to_add):
        for index in range(self.num_of_values):
            self.values[index]  = number_to_add
        return self.values

def main():
    myVals = MyValues( [1, 2, 3, 4, 5] )
    print( myVals.add_number(10) )
    
if __name__ == '__main__':
    main()

Output:

[11, 12, 13, 14, 15]
  •  Tags:  
  • Related