0

I have this code that stores a person's name, age and funds. I am trying to write a method that can take "age" or "funds", along with a number, and increase the given attribute by that number.

class Actor:
    def __init__(self, name, age, funds):
        self.name
        self.age = age
        self.funds = funds

    def increase_age(self, increase_amount=1):
        self.age = self.age + increase_amount

    def increase_attrib(self, attrib, increase_amount=1):
        self.attrib = self.attrib + increase_amount

a = Actor("Andrea", 32, 10000)

a.increase_age() works fine: calling it increases the age of Andrea to 33, just as expected. However, a.increase_attrib("age") gives an error, saying AttributeError: 'Actor' object has no attribute 'attrib'. a.increase_attrib("funds") gives similar results.

If I just say a.increase_attrib(age) (without the quotes) I get a NameError, which is what I expected.

By my understanding, giving the parameter "age" to increase_attrib() should mean that the attrib mentioned becomes age, so that increase_attrib() references self.age instead of self.attrib. Apparently, I was wrong.

Now, I could just use increase_age() instead, but then I'd have to make different methods for age and funds, and even more methods once I add other features to Actor, like location, gender, and nationality.

What do I need to do so that I can pass the name of an attribute to a method and have it change that attribute?

Somatic
  • 193
  • 7
  • Are you after `setattr(self, attrib, getattr(self, attrib) + increase_amount)`? If so, see http://stackoverflow.com/q/1167398/3001761 – jonrsharpe Jan 14 '16 at 23:15

1 Answers1

3

You are looking for setattr:

setattr(obj, 'foo', 42)

Is the same as

obj.foo = 42

So for your example:

def increase_attrib(self, attrib, increase_amount=1):
    setattr(self, attrib, getattr(self, attrib, 0) + increase_amount)
Messa
  • 24,321
  • 6
  • 68
  • 92