Idan Gazit
Idan Gazit

Reputation: 2570

How do I increment an attribute at runtime using getattr/setattr?

I have a class with ten different counters. I need to increment one or another of these at runtime, and the increment method is told the name of the counter to increment.

I'm wondering if there's a cleaner way than this:

def increment(self, name):
    """Increments a counter specified by the 'name' argument."""
    setattr(self, name, getattr(self, name) + 1)

Upvotes: 8

Views: 1913

Answers (1)

Sven Marnach
Sven Marnach

Reputation: 602625

You could store the counters in a dictionary instead of in attributes.

Alternatively, you could use

def increment(self, name):
    """Increments a counter specified by the 'name' argument."""
    self.__dict__[name] += 1

It's up to you to decide if this is "cleaner".

Upvotes: 7

Related Questions