2

I have the following Python object:

class car(object):

    def __init__(self, name, cost, type, speed):
        self.name = name
        self.cost = cost
        self.type = type
        self.speed = speed

    def get_name(self): return self.name
    def get_cost(self): return self.cost
    def get_type(self): return self.type
    def get_speed(self): return self.speed

I then want to perform the same operation to some parameters of the object. I want to add 1 to each specified attribute.

One way of doing this is obviously:

obj = car('volvo', 100, 0, 5)
obj.cost = obj.cost + 1
obj.type = obj.type + 1
obj.speed = obj.speed + 1

But this wastes several lines of code. Is there a way to do something like:

attributesToModify = ['cost', 'type', 'speed']
for e in attributesToModify:
    obj.e = obj.e + 1
Apollo
  • 8,874
  • 32
  • 104
  • 192
  • Take a look at [Getting dynamic attribute in python](https://stackoverflow.com/questions/13595690/getting-dynamic-attribute-in-python) – LinkBerest Oct 04 '15 at 21:50

2 Answers2

3

You could just add a method to your class:

 def inc(self, i):
    self.cost += i
    self.type += i
    self.speed += i

Then pass in the increment:

obj.inc(1)
Padraic Cunningham
  • 176,452
  • 29
  • 245
  • 321
  • This wouldn't be best for my actual use case. I have 5 attributes and I want to vary them by +/- the attributes value by 20% and only vary each attribute one at a time. – Apollo Oct 04 '15 at 21:57
  • @Apollo, that can all be done in the method. Once you know what you want to do you can take other args. – Padraic Cunningham Oct 04 '15 at 21:57
2

I think you are looking to use setattr and getattr:

attributesToModify = ['cost', 'type', 'speed']
for e in attributesToModify:
    setattr(obj, e, getattr(obj, e) + 1)
idjaw
  • 25,487
  • 7
  • 64
  • 83