The Show Example
getattr() SyntaxThe syntax of getattr(object, name[, default]) The above syntax is equivalent to: object.name getattr() Parameters
getattr() Return Value
Example 1: How getattr() works in Python?
Output The age is: 23 The age is: 23 Example 2: getattr() when named attribute is not found
Output The sex is: Male AttributeError: 'Person' object has no attribute 'sex' The named attribute sex is not present in the class Person. So, when calling getattr(object, name[, default])5, it returns Male. But, if we don't provide any default value, when the named attribute sex is not found, it raises an getattr(object, name[, default])2 saying the object has no sex attribute. Before we jump into how The 1 method returns the value of the attribute of an object. If the named attribute does not exist, default is returned if provided, otherwise 2 is raised.Syntax:
Parameters:
Return Value:
The following example demonstrates the 1 method.Example: getattr() Copy
Output
Above, 5 returns the value of the 6 property of the 7 object, which is 8. It always returns the latest value even after updating a property value.If the attribute specified in the argument is not found, an 2 exception is thrown.Example: getattr() Copy
Output
The default parameter can be passed to avoid the above error, which returns the default value if the attribute is not found. Example: getattr() Copy
Output
Instead of 1 method, the 1 operator can also be used to access the attribute value if you are sure that an object has that attribute. |