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.
getattr(object, name[, default])
Python getattr()
takes 3 parameters.
AttributeError
is raised.>>> 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.