Practical Attribute Manipulation
Now that we've covered the basics of setting and manipulating object attributes, let's explore some practical applications of these techniques.
Dynamic Attribute Creation
One common use case for attribute manipulation is the ability to dynamically create attributes at runtime. This can be particularly useful when working with data-driven applications or when you need to add new features to an existing object.
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
person = Person("John", 30)
setattr(person, "occupation", "Software Engineer")
print(person.occupation) ## Output: Software Engineer
Attribute Validation
Another practical use case for attribute manipulation is attribute validation. You can use the __setattr__()
method to enforce certain rules or constraints when setting an attribute.
class BankAccount:
def __init__(self, owner, balance):
self.owner = owner
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("John", 1000)
account.balance = -500 ## This will raise a ValueError
Attribute Introspection
You can use the built-in functions like dir()
, vars()
, and __dict__
to introspect an object's attributes and their values.
class Book:
def __init__(self, title, author, pages):
self.title = title
self.author = author
self.pages = pages
book = Book("The Great Gatsby", "F. Scott Fitzgerald", 180)
print(dir(book)) ## Output: ['__class__', '__delattr__', ..., 'author', 'pages', 'title']
print(vars(book)) ## Output: {'title': 'The Great Gatsby', 'author': 'F. Scott Fitzgerald', 'pages': 180}
print(book.__dict__) ## Output: {'title': 'The Great Gatsby', 'author': 'F. Scott Fitzgerald', 'pages': 180}
These techniques can be used to build more flexible and dynamic applications, as well as to implement advanced object-oriented programming patterns.