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.

    1. class Person:
    2. name = 'Andrea'
    3. print(getattr(Person, 'name'))
    4. setattr(Person, 'name', 'Ilaria')
    5. 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!

     
     

    Please feel free to point out any errors or typos, or share suggestions to improve these notes. English isn't my first language, so if you notice any mistakes, let me know, and I'll be sure to fix them.

    FacebookTwitterLinkedinLinkedin
    knowledge base

    Python Classes