Python getattr() Syntax
getattr(object, name[, default])
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
- 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
getattr() function which is not associated with the object, instead of throwing an error, the default value is displayed.