Mastering Python's hasattr(), getattr(), and setattr() for Dynamic Attribute Handling

Mastering Python's hasattr(), getattr(), and setattr() for Dynamic Attribute Handling ๐Ÿง 

When you need to check, retrieve, or set object attributes dynamically in Python, hasattr(), getattr(), and setattr() are the tools you need. Let’s walk through each with simple and real-world examples.

Python object attributes icon

✅ Example class

# Example class
class User:
    def __init__(self, name):
        self.name = name

user = User("Alice")

✅ hasattr(): Check if attribute exists

# hasattr: Check if attribute exists
print(hasattr(user, 'name'))   # True
print(hasattr(user, 'email'))  # False

✅ getattr(): Retrieve attribute value

# getattr: Get attribute value
print(getattr(user, 'name'))               # Alice
print(getattr(user, 'email', 'Not set'))   # Not set

✅ setattr(): Dynamically assign a new attribute

# setattr: Dynamically assign new attribute
setattr(user, 'email', 'alice@example.com')
print(user.email)  # alice@example.com

Using these functions makes your code more flexible and scalable—especially in cases like plugin systems, custom serializers, or dynamic configuration loaders.

Static code is predictable, but dynamic code is powerful. Master Python’s introspection and let your objects adapt. ๐Ÿš€

Icons by Flaticon

Comments

Popular posts from this blog

Mastering Python Generators and yield: Efficient Iteration Explained

Mastering Python Sets: Remove Duplicates and Do More

Python Logging Module: Basics and Best Practices ๐Ÿ“