Using the setattr Function in Python
In Python, the setattr
function allows you to modify an attribute of a class from outside the class itself.
Syntax
setattr(object, attribute, value)
A Practical Example
In this example, I'll create a simple Person
class with an internal attribute called name
.
- class Person:
- name = 'Andrea'
- print(getattr(Person, 'name'))
- setattr(Person, 'name', 'Ilaria')
- print(getattr(Person, 'name'))
Initially, the name
attribute is set to 'Andrea'.
In line 3, the getattr() function reads and prints the value of the 'name' attribute.
Andrea
In line 4, the value of the 'name' attribute is changed to 'Ilaria' using the setattr() function.
Line 5 then reads and prints the updated value of the 'name' attribute using the getattr() function.
Ilaria
As a result, the 'name' attribute in the Person
class now holds the new value.
It's no longer the original one.
And that's how it works!