Python’s magic method __getattr__()
implements the built-in getattr()
function that returns the value associated with a given attribute name. Additionally, __getattr__()
is called if the normal attribute access (e.g., my_object.my_attribute
) results in an AttributeError
.
We call this a “Dunder Method” for “Double Underscore Method” (also called “magic method”). To get a list of all dunder methods with explanation, check out our dunder cheat sheet article on this blog.
Syntax and Example
object.__getattr__(self, attr_name)
Let’s have a look at an example where you override the __getattr__
magic method of a custom class Person
to simply print out the string 'hello world'
when calling the getattr()
built-in function.
class Person: def __getattr__(self, attr_name): print('hello world') alice = Person() getattr(alice, 'age') # hello world
Note that __getattr__()
is also called if you try to access an attribute that doesn’t exist and, thus, would yield an AttributeError
otherwise.
class Person: def __getattr__(self, attr_name): print('hello world') alice = Person() alice.age # attribute doesn't exist! # hello world
Here’s what would’ve happened in the same scenario without defining the __getattr__()
magic method:
class Person: pass alice = Person() alice.age # attribute doesn't exist!
As the alice.age
attribute doesn’t exist, Python raises an AttributeError
:
Traceback (most recent call last): File "C:\Users\xcent\Desktop\code.py", line 6, in <module> alice.age # attribute doesn't exist! AttributeError: 'Person' object has no attribute 'age'
You can see this scenario next in our recap on the built-in setattr()
function.
Background getattr()
Python’s built-in getattr(object, string)
function returns the value of the object
‘s attribute with name string
.
If this doesn’t exist, it returns the value provided as an optional third default
argument.
If that doesn’t exist either, it raises an AttributeError
.
An example is getattr(porsche, 'speed')
which is equivalent to porsche.speed
.
# Define class with one attribute class Car: def __init__(self, brand, speed): self.brand = brand self.speed = speed # Create object porsche = Car('porsche', 100) tesla = Car('tesla', 110) # Two alternatives to get instance attributes: print(getattr(porsche, 'brand') + " " + str(getattr(porsche, 'speed'))) print(tesla.brand + " " + str(tesla.speed)) # Get an attribute that doesn't exist with default argument: print(getattr(porsche, 'color', 'red'))
Output:
porsche 100 tesla 110 red
Further Reading:
- Python
__delattr__()
magic method - Python
setattr()
built-in function - Python
getattr()
built-in function - Python
__getattr__()
vs__getattribute__()
- https://docs.python.org/3/reference/datamodel.html
Where to Go From Here?
Enough theory. Let’s get some practice!
Coders get paid six figures and more because they can solve problems more effectively using machine intelligence and automation.
To become more successful in coding, solve more real problems for real people. That’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?
You build high-value coding skills by working on practical coding projects!
Do you want to stop learning with toy projects and focus on practical code projects that earn you money and solve real problems for people?
🚀 If your answer is YES!, consider becoming a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.
If you just want to learn about the freelancing opportunity, feel free to watch my free webinar “How to Build Your High-Income Skill Python” and learn how I grew my coding business online and how you can, too—from the comfort of your own home.