getattr is a Python built-in function used to access a named attribute on an object.
The function's schematics are as follows:
getattr(object:object, name:str[, default:object]) -> value
where object
is the object, name
is the named attribute, and default
, if supplied, is the default value to return if the attribute can not be found. If default
is not supplied and the object can not be found, an AttributeError
is thrown.
Below is a demonstration of the function's features:
>>> class Test:
... def __init__(self):
... self.attr = 1
...
>>> myTest = Test()
>>> getattr(myTest, 'attr')
1
>>> getattr(myTest, 'attr2', 'No attribute by that name')
'No attribute by that name'
>>> getattr(myTest, 'attr2')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: Test instance has no attribute 'attr2'
>>>