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.
✅ 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
Post a Comment