Python : Dynamically access or modify object attributes [ getattr and setattr ]

python @ Freshers.in

getattr and setattr are built-in Python functions that allow you to dynamically get and set attributes of an object, respectively. They are useful when you need to interact with object attributes whose names are determined at runtime or when you want to write more generic code that can handle different sets of attributes.

getattr(obj, attr, default=None):

obj: The object whose attribute you want to get.
attr: A string representing the name of the attribute you want to get.
default: An optional value that will be returned if the attribute is not found. If not specified, an AttributeError is raised when the attribute is not found.
Example:

class MyClass:
    def __init__(self):
        self.my_attr = "Hello, World!"

my_instance = MyClass()
attribute_value = getattr(my_instance, "my_attr")  # "Hello, World!"
non_existent_attr = getattr(my_instance, "non_existent_attr", "Default Value")  # "Default Value"

setattr(obj, attr, value):

obj: The object whose attribute you want to set.
attr: A string representing the name of the attribute you want to set.
value: The value you want to set the attribute to.
Example:

class MyClass:
    def __init__(self):
        self.my_attr = "Hello, World!"

my_instance = MyClass()
setattr(my_instance, "my_attr", "New value")
print(my_instance.my_attr)  # "New value"

setattr(my_instance, "new_attr", 42)
print(my_instance.new_attr)  # 42

In both examples, getattr and setattr are used to access and modify the attributes of the MyClass object dynamically, using attribute names as strings. This allows you to write more flexible and generic code that can handle different sets of attributes.

Here’s a real-world example using a simple class representing a user profile:

class UserProfile:
    def __init__(self, name, email, age):
        self.name = name
        self.email = email
        self.age = age

    def display(self):
        print(f"Name: {self.name}, Email: {self.email}, Age: {self.age}")

Suppose you are building an application that allows users to update their profiles. You receive an update request containing a dictionary with attribute names as keys and new values as values:

update_request = {
    "name": "John Doe",
    "age": 30
}

You can use getattr and setattr to apply these updates to the user profile:

def update_profile(user_profile, updates):
    for attr, value in updates.items():
        if hasattr(user_profile, attr):  # Check if the attribute exists
            old_value = getattr(user_profile, attr)
            setattr(user_profile, attr, value)
            print(f"Updated {attr}: {old_value} -> {value}")
        else:
            print(f"Attribute '{attr}' not found in UserProfile")

user = UserProfile("Jane Doe", "jane.doe@example.com", 28)
user.display()

update_profile(user, update_request)
user.display()

In this example, getattr and setattr allow you to access and modify the UserProfile object’s attributes dynamically based on the update_request dictionary. This can be helpful in situations where you don’t know beforehand which attributes need to be updated or when the code should be flexible enough to handle different sets of attributes.

Refer more on python here :

Author: user

Leave a Reply