Python getattr()
function is used to fetch the value of the object’s named attribute. The name of the attribute must be a string. It returns the default value if no attribute of that object is found.
Python getattr() Syntax
getattr(object, name[, default])
Python getattr()
takes 3 parameters.
- object (required) – The object whose attribute is to be returned.
- name (required) – Must be a string. Name of attribute to be returned. If not found default value is returned and if the default is not defined
AttributeError
is raised. - default (optional) – Default value to be returned of the named attribute does not exist.
Python getattr() Example
>>> class Car:
def __init__(self,model):
self.model = model
>>> obj = Car('La Ferrari')
>>> getattr(obj, 'model')
'La Ferrari'
>>> getattr(obj, 'price','$1 million')
'$1 million'
As you can see in above example, the object obj
of class Car
has one attribute model
which can be accessed using getattr()
function. When we try to access to attribute price
using getattr()
function which is not associated with the object, instead of throwing an error, the default value is displayed.