Skip to content

How to Access and Modify Attributes in Python Objects

Learn how to use dot notation, getattr(), and setattr() to read and update Python object attributes dynamically or statically for effective OOP development.

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

john = Person("John", 30)

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)

print(f"Original Name: {john.name}")

john.age = 31
print(f"Updated Age: {john.age}")

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"

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"

setattr(john, attribute_to_change, 35)

print(f"New age: {john.age}")

Output:

New age: 35

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:
    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)

address = getattr(john, "address", "Not Available")
print(f"Address: {address}")

Output:

Address: Not Available

Conclusion

Managing object attributes is a core Python skill:

  1. Use Dot Notation (obj.name) for standard, readable code where attribute names are known.
  2. Use getattr(obj, 'name') and setattr(obj, 'name', val) for dynamic scenarios where attribute names are strings.
  3. Always provide a default value when using getattr() if there is a risk the attribute might be missing to avoid AttributeError.
Navigation