Python getattr() Function
The Python getattr() function returns the value of specified attribute of specified object. It raises an exception when required attribute is not found in the object. There is a optional parameter in this function, which can be used to handle such exception.
Syntax
getattr(object, attribute, default)
Parameters
object |
Required. An object |
attribute |
Required. attribute which need to checked in object. |
default |
Optional. returns a value when required attribute is not found in the object. |
Example:
In the example below, getattr() function is used to get the value of specified attribute of the given class.
class MyClass: name = 'John' age = 25 city = 'London' print(getattr(MyClass, 'age')) print(getattr(MyClass, 'hobby'))
The output of the above code will be:
25 Traceback (most recent call last): File "Main.py", line 7, in <module> print(getattr(MyClass, 'hobby')) AttributeError: type object 'MyClass' has no attribute 'hobby'
Example:
In this example, getattr() function is used with default argument. The default value is returned when the specified attribute is not found in the object.
class MyClass: name = 'John' age = 25 city = 'London' print(getattr(MyClass, 'age', 'attribute not found.')) print(getattr(MyClass, 'hobby', 'attribute not found.'))
The output of the above code will be:
25 attribute not found.
❮ Python Built-in Functions