Using setattr() in python
The Python docs say all that needs to be said, as far as I can see.
setattr
(object, name, value)This is the counterpart of
getattr()
. The arguments are an object, a string and an arbitrary value. The string may name an existing attribute or a new attribute. The function assigns the value to the attribute, provided the object allows it. For example,setattr(x, 'foobar', 123)
is equivalent tox.foobar = 123
.
To add to the other answers, a common use case I have found for setattr()
is when using configs. It is common to parse configs from a file (.ini file or whatever) into a dictionary. So you end up with something like:
configs = {'memory': 2.5, 'colour': 'red', 'charge': 0, ... }
If you want to then assign these configs to a class to be stored and passed around, you could do simple assignment:
MyClass.memory = configs['memory']
MyClass.colour = configs['colour']
MyClass.charge = configs['charge']
...
However, it is much easier and less verbose to loop over the configs, and setattr()
like so:
for name, val in configs.items():
setattr(MyClass, name, val)
As long as your dictionary keys have the proper names, this works very well and is nice and tidy.
*Note, the dict keys need to be strings as they will be the class object names.
You are setting self.name
to the string "get_thing"
, not the function get_thing
.
If you want self.name
to be a function, then you should set it to one:
setattr(self, 'name', self.get_thing)
However, that's completely unnecessary for your other code, because you could just call it directly:
value_returned = self.get_thing()
Setattr: We use setattr to add an attribute to our class instance. We pass the class instance, the attribute name, and the value. and with getattr we retrive these values
For example
Employee = type("Employee", (object,), dict())
employee = Employee()
# Set salary to 1000
setattr(employee,"salary", 1000 )
# Get the Salary
value = getattr(employee, "salary")
print(value)