getattr()
Published May 25, 2023
Contribute to Docs
The built-in getattr() function returns the value of the named property in a specified object/Class.
Syntax
getattr(object, name, default)
The getattr()
method takes at least 2 parameters:
object
, the given objectname
, a string with the name of the attributedefault
, (optional) a value to be returned when the named attribute does not exist
Examples
Example 1
class Cat:hobby = 'sleeping'age = 2pet = Cat()attr = getattr(pet, 'age')print("My cat is", attr, "years old.")
This code will return:
My cat is 2 years old.
Example 2
class Cat:hobby = 'sleeping'age = 2pet = Cat()attr = getattr(pet, 'love')print("My cat's favourite food is", attr)
This code will output an error, this because the Cat
object does not have an attribute named love
, and we did not set default
parameter:
Traceback (most recent call last):File "main.py", line 6, in <module>attr = getattr(pet, 'love')AttributeError: 'Cat' object has no attribute 'love'
Example 3
class Cat:hobby = 'sleeping'age = 2pet = Cat()attr = getattr(pet, 'love', 'tuna')print("My cat's favourite food is", attr)
This code will return:
My cat's favourite food is tuna
Codebyte Example
Use getattr()
to get the value of the named property in a specified object/class:
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.