getattr()
The built-in getattr() function allows you to retrieve the value of an attribute from an object. If the specified attribute doesn’t exist, it can return a default value if provided. Otherwise, it raises an AttributeError exception:
>>> class Person:
... def __init__(self, name, age):
... self.name = name
... self.age = age
...
>>> jane = Person("Jane", 25)
>>> getattr(jane, "name")
'Jane'
>>> getattr(jane, "age")
25
>>> getattr(jane, "missing", None)
None
getattr() Signatures
getattr(object, name)
getattr(object, name, default)
Arguments
| Argument | Description |
|---|---|
object |
The object whose attribute value you want to retrieve. |
name |
A string representing the name of the attribute to retrieve. |
default |
An optional value to return if the attribute isn’t found. |
Return Value
- If the attribute exists,
getattr()returns the value of the attribute. - If the attribute doesn’t exist and a
defaultvalue is provided, it returns thedefaultvalue. - If the attribute doesn’t exist and no
defaultvalue is provided, it raises anAttributeErrorexception.
To see how these three rules play out, try the widget below. Pick an attribute name, toggle whether you pass a default, and watch which branch getattr() takes:
The examples that follow walk through each of these three branches in code.
getattr() Examples
With the name of an existing attribute:
>>> class Circle:
... def __init__(self, radius):
... self.radius = radius
...
>>> circle = Circle(10)
>>> getattr(circle, "radius")
10
With a non-existent attribute and a default value:
>>> getattr(circle, "diameter", 0)
0
With a non-existent attribute without a default value:
>>> getattr(circle, "diameter")
Traceback (most recent call last):
...
AttributeError: 'Circle' object has no attribute 'diameter'
getattr() Common Use Cases
The most common use cases for the getattr() function include:
- Accessing object attributes dynamically when attribute names are determined at runtime.
- Providing a
defaultvalue for non-existent attributes to avoid exceptions. - Accessing methods dynamically to call them later.
getattr() Real-World Example
Consider a situation where you have a list of objects, and you need to retrieve a specific attribute from each object, handling cases where the attribute might be missing by using a default value:
>>> class Car:
... def __init__(self, make, model, year):
... self.make = make
... self.model = model
... self.year = year
...
>>> cars = [
... Car("Toyota", "Corolla", 2020),
... Car("Ford", "Mustang", 2018),
... Car("Tesla", "Model S", 2022)
... ]
>>> for car in cars:
... print(getattr(car, "color", "Unknown"))
...
Unknown
Unknown
Unknown
In this example, getattr() helps retrieve the .color attribute from each Car object, providing a default value of "Unknown" when the attribute isn’t present.
Related Resources
Tutorial
Object-Oriented Programming (OOP) in Python
In this tutorial, you'll learn all about object-oriented programming (OOP) in Python. You'll learn the basics of the OOP paradigm and cover concepts like classes and inheritance. You'll also see how to instantiate an object from a class.
For additional information on related topics, take a look at the following resources:
- Python Classes: The Power of Object-Oriented Programming (Tutorial)
- Python's Magic Methods: Leverage Their Power in Your Classes (Tutorial)
- A Conceptual Primer on OOP in Python (Course)
- Intro to Object-Oriented Programming (OOP) in Python (Course)
- Object-Oriented Programming (OOP) in Python (Quiz)
- Class Concepts: Object-Oriented Programming in Python (Course)
- Inheritance and Internals: Object-Oriented Programming in Python (Course)
- Python Classes - The Power of Object-Oriented Programming (Quiz)
- Python's Magic Methods in Classes (Course)
- Python's Magic Methods: Leverage Their Power in Your Classes (Quiz)