How to Access and Modify Attributes in Python Objects
In Python, everything is an object. Understanding how to interact with these objects, specifically how to read (access) and write (modify) their data, is fundamental to Object-Oriented Programming (OOP). Whether you are working with simple data structures or complex systems, you will constantly need to retrieve or update object properties.
This guide covers the standard dot notation method for static access and the built-in getattr() and setattr() functions for dynamic attribute manipulation.
Understanding Classes and Objects
Before accessing attributes, it is important to understand the structure. A Class is a blueprint, and an Object is an instance of that blueprint. Attributes are variables bound to that specific object.
class Person:
def __init__(self, name, age):
self.name = name # Attribute 1
self.age = age # Attribute 2
# Create an object (instance)
john = Person("John", 30)
The self parameter in Python methods refers to the current instance of the class. It is used to access variables that belong to the class.
Method 1: Dot Notation (Standard Approach)
The most common and readable way to interact with an object is using dot notation (object.attribute).
Accessing and Modifying
You simply type the object name, followed by a dot, and then the attribute name.
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
john = Person("John", 30)
# ✅ Accessing attributes
print(f"Original Name: {john.name}")
# ✅ Modifying attributes
john.age = 31
print(f"Updated Age: {john.age}")
# ✅ Creating a NEW attribute dynamically
john.job = "Developer"
print(f"New Job Attribute: {john.job}")
Output:
Original Name: John
Updated Age: 31
New Job Attribute: Developer
Method 2: Dynamic Access with getattr and setattr
Sometimes you do not know the name of the attribute until the code runs (e.g., the attribute name is stored in a string variable from user input or a database). In these cases, dot notation will not work.
Using getattr()
The getattr(object, name) function retrieves the value of an attribute where name is a string.
john = Person("John", 30)
attribute_to_lookup = "name"
# ✅ Dynamic Access
value = getattr(john, attribute_to_lookup)
print(f"Value of '{attribute_to_lookup}': {value}")
Output:
Value of 'name': John
Using setattr()
The setattr(object, name, value) function sets the value of an attribute where name is a string.
john = Person("John", 30)
attribute_to_change = "age"
# ✅ Dynamic Modification
setattr(john, attribute_to_change, 35)
# Verify change
print(f"New age: {john.age}")
Output:
New age: 35
This approach is extremely powerful when converting dictionaries to objects or processing data where keys match object attribute names.
Handling Missing Attributes Safely
Attempting to access an attribute that does not exist results in an AttributeError.
The Error Scenario
john = Person("John", 30)
try:
# ⛔️ Incorrect: 'address' was never defined
print(john.address)
except AttributeError as e:
print(f"Error: {e}")
Output:
Error: 'Person' object has no attribute 'address'
The Solution: Default Values with getattr
The getattr() function accepts an optional third argument: a default value to return if the attribute is missing. This prevents the code from crashing.
john = Person("John", 30)
# ✅ Correct: Provide a default value
address = getattr(john, "address", "Not Available")
print(f"Address: {address}")
Output:
Address: Not Available
Conclusion
Managing object attributes is a core Python skill:
- Use Dot Notation (
obj.name) for standard, readable code where attribute names are known. - Use
getattr(obj, 'name')andsetattr(obj, 'name', val)for dynamic scenarios where attribute names are strings. - Always provide a default value when using
getattr()if there is a risk the attribute might be missing to avoidAttributeError.