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)
What is getattr() used for in Python? We use the Python setattr() function to assign a value to an object's attribute. There might arise a situation where we might want to fetch the values assigned to the attributes. To provide this functionality, Python getattr() built-in function is used.
The setattr() function sets the value of the specified attribute of the specified object.
__getattr__Called when an attribute lookup has not found the attribute in the usual places (i.e. it is not an instance attribute nor is it found in the class tree for self).
If the specified attribute does not exist in the class, the setattr() creates a new attribute to an object or class and assigns the specified value to it. The following assigns a new attribute to the class itself. Note that this new attribute can only be attached to the specified object.
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".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With