Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

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)
  • I'm not terribly worried about race conditions and the like.
  • No, you can't change the way the function is called. Obviously, the real code is a little less trivial than the example.
like image 799
Idan Gazit Avatar asked Mar 13 '11 12:03

Idan Gazit


People also ask

What is Setattr () and Getattr () used for?

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.

What is Setattr () used for to set an attribute?

The setattr() function sets the value of the specified attribute of the specified object.

What is __ Getattr __ in Python?

__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).

What will happen if the attribute is not found in Setattr () method?

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.


1 Answers

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".

like image 111
Sven Marnach Avatar answered Sep 27 '22 16:09

Sven Marnach