accessing object attributes
Accessing Object Attributes with getattr() and setattr()
We have already used dot notation to store and access an object’s data.
class Student:
def __init__(self, name, marks):
self.name = name
self.marks = marks
student1 = Student("Rahul", 85)
print(student1.name)
print(student1.marks)
Output:
Rahul 85
Here, the attribute names name and marks are written directly in the program.
Now suppose the attribute we want to access is stored in a variable:
attribute_name = "marks"
How can we use this variable to read the student’s marks?
Reading an Attribute Using Its Name
Python provides the built-in function getattr() to access an attribute using its name as a string.
attribute_name = "marks" value = getattr(student1, attribute_name) print(value)
Output:
85
The basic syntax is:
getattr(object, attribute_name)
In our example:
| Argument | Value | Meaning |
|---|---|---|
| object | student1 | The object whose attribute we want to access |
| attribute_name | "marks" | The name of the attribute |
For this object, these statements return the same value:
print(student1.marks) print(getattr(student1, "marks"))
Output:
85 85
Dot notation is convenient when we know the attribute name while writing the code. getattr() is useful when the name comes from a variable, user input, or a collection of names.
A Variable after the Dot Is Not Substituted
Consider:
attribute_name = "marks" print(student1.attribute_name)
Python looks for an attribute literally named attribute_name. It does not read the variable and replace it with "marks".
Because our object has no attribute named attribute_name, this raises an AttributeError.
Use getattr() when the attribute name is stored in a variable:
print(getattr(student1, attribute_name))
Output:
85
Choosing an Attribute through User Input
We can allow the user to choose which student detail to display.
class Student:
def __init__(self, name, marks):
self.name = name
self.marks = marks
student1 = Student("Rahul", 85)
attribute_name = input("Enter attribute name (name/marks): ")
value = getattr(student1, attribute_name)
print("Value:", value)
Sample run:
Enter attribute name (name/marks): marks Value: 85
Another run could display the name:
Enter attribute name (name/marks): name Value: Rahul
The same statement accesses different attributes depending on the input.
Attribute names are case-sensitive. "name" and "Name" refer to different names.
Handling an Attribute That Does Not Exist
Our student currently has no grade attribute.
print(getattr(student1, "grade"))
This raises:
AttributeError: 'Student' object has no attribute 'grade'
We can supply a default value as the third argument:
print(getattr(student1, "grade", "Not assigned"))
Output:
Not assigned
The syntax is:
getattr(object, attribute_name, default_value)
If the attribute exists, its value is returned. Otherwise, the default is returned.
print(getattr(student1, "name", "Not available")) print(getattr(student1, "grade", "Not assigned"))
Output:
Rahul Not assigned
The default does not create the missing attribute. It only provides a fallback result for that lookup.
We can now improve the input example:
attribute_name = input("Enter attribute name: ")
value = getattr(student1, attribute_name, "Attribute not found")
print("Value:", value)
Sample run:
Enter attribute name: grade Value: Attribute not found
Updating an Attribute Using setattr()
To update marks using dot notation, we write:
student1.marks = 90
We can perform the same assignment using setattr():
setattr(student1, "marks", 90) print(student1.marks)
Output:
90
The syntax is:
setattr(object, attribute_name, value)
For this call:
setattr(student1, "marks", 90)
the arguments mean:
| Argument | Purpose |
|---|---|
| student1 | Selects the object |
| "marks" | Selects the attribute |
| 90 | Supplies the new value |
Like getattr(), setattr() accepts an attribute name stored in a variable.
attribute_name = "marks" new_value = 95 setattr(student1, attribute_name, new_value) print(student1.marks)
Output:
95
setattr() performs the assignment and returns None. To see the updated value, read the attribute afterward.
Adding a New Attribute
For our ordinary Student class, setattr() can also add an attribute that does not yet exist.
setattr(student1, "grade", "A") print(student1.grade)
Output:
A
This has the same effect as:
student1.grade = "A"
We can read the new attribute using either approach:
print(student1.grade) print(getattr(student1, "grade"))
Output:
A A
The new attribute belongs to this particular object. It is not automatically added to other students.
student2 = Student("Anjali", 92)
print(getattr(student1, "grade", "Not assigned"))
print(getattr(student2, "grade", "Not assigned"))
Output:
A Not assigned
Not every Python object allows new attributes to be added. The behavior shown here applies to the simple user-defined class we are using.
Reading Several Attributes in a Loop
Suppose we want to display a selected set of student details.
We can store the attribute names in a list and read them one by one.
class Student:
def __init__(self, name, marks):
self.name = name
self.marks = marks
student1 = Student("Rahul", 85)
attributes = ["name", "marks", "grade"]
for attribute_name in attributes:
value = getattr(student1, attribute_name, "Not assigned")
print(f"{attribute_name}: {value}")
Output:
name: Rahul marks: 85 grade: Not assigned
During each iteration, attribute_name contains a different string. getattr() uses that string to select the attribute.
This allows one statement to handle several attribute names.
A Complete Example
The following program reads student details, updates marks, and adds an email address.
class Student:
def __init__(self, name, roll_number, marks):
self.name = name
self.roll_number = roll_number
self.marks = marks
student1 = Student("Rahul", 101, 85)
# Read existing attributes
print("Name:", getattr(student1, "name"))
print("Initial Marks:", getattr(student1, "marks"))
# Update an existing attribute
setattr(student1, "marks", 93)
# Add a new attribute
setattr(student1, "email", "rahul@example.com")
# Display selected attributes
print()
print("Updated Student Details")
attributes = ["name", "roll_number", "marks", "email", "grade"]
for attribute_name in attributes:
value = getattr(student1, attribute_name, "Not assigned")
print(f"{attribute_name}: {value}")
Output:
Name: Rahul Initial Marks: 85 Updated Student Details name: Rahul roll_number: 101 marks: 93 email: rahul@example.com grade: Not assigned
Practice
Create a Product class with name, price, and quantity attributes.
product1 = Product("Notebook", 50, 4)
Then complete these tasks:
-
Read the price using getattr().
-
Update the price to 60 using setattr().
-
Add a category attribute with the value "Stationery".
-
Read a missing discount attribute with a default value of 0.
-
Display the product’s attributes using a loop.
Expected values after the updates:
name: Notebook price: 60 quantity: 4 category: Stationery discount: 0
The discount value should come from the fallback argument; you do not need to create that attribute.
These functions access and assign attributes using names supplied as strings. They do not themselves define validation rules. In the next lesson, we will use property() to connect attribute access and assignment to getter and setter methods.