Practical Techniques and Examples
Now that you understand the core operations for manipulating object attributes, let's explore some practical techniques and examples.
Dynamic Attribute Creation
You can use setattr()
to create new attributes on the fly, even if they don't exist in the object's class definition.
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
person = Person("Alice", 30)
setattr(person, "email", "[email protected]")
print(person.email) ## Output: [email protected]
Iterating over Attributes
You can use the vars()
function to get a dictionary of an object's attributes, which you can then iterate over.
class Book:
def __init__(self, title, author, genre):
self.title = title
self.author = author
self.genre = genre
book = Book("The Great Gatsby", "F. Scott Fitzgerald", "Fiction")
for attr, value in vars(book).items():
print(f"{attr}: {value}")
This will output:
title: The Great Gatsby
author: F. Scott Fitzgerald
genre: Fiction
Attribute Validation
You can use getattr()
and setattr()
to implement attribute validation, ensuring that the attributes meet certain criteria.
class BankAccount:
def __init__(self, balance):
self.balance = balance
def __setattr__(self, name, value):
if name == "balance" and value < 0:
raise ValueError("Balance cannot be negative.")
super().__setattr__(name, value)
account = BankAccount(1000)
account.balance = 500 ## This works
account.balance = -100 ## Raises ValueError: Balance cannot be negative.
Attribute Monitoring
You can use the __getattr__()
and __setattr__()
methods to monitor and log changes to an object's attributes.
class LoggingObject:
def __init__(self):
self._attribute_changes = []
def __getattr__(self, name):
return self.__dict__.get(name, None)
def __setattr__(self, name, value):
self._attribute_changes.append((name, value))
super().__setattr__(name, value)
obj = LoggingObject()
obj.x = 10
obj.y = 20
print(obj._attribute_changes) ## Output: [('x', 10), ('y', 20)]
These examples demonstrate how you can leverage the core attribute manipulation operations to create more dynamic and robust Python applications.