English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
The getattr() method returns the value of the named attribute of the object. If not found, it will return the default value provided to the function.
The syntax of the getattr() method is:
getattr(object, name[, default])
The above syntax is equivalent to:
object.name
The getattr() method takes multiple parameters:
object -The object to return the named attribute value of
name -A string containing the name of the attribute
default (optional) -The value returned when the named attribute is not found
The getattr() method returns:
The value of the named attribute of the given object
default if the named attribute is not found
AttributeError exception if the named attribute is not found and no default value is defined
class Person: age = 23 name = "Adam" person = Person() print('Age is:', getattr(person, "age")) print('Age is:', person.age)
When running the program, the output is:
Age is: 23 Age is: 23
class Person: age = 23 name = "Adam" person = Person() # When a default value is provided print('Gender is:', getattr(person, 'sex', 'Male')) # When no default value is provided print('Gender is:', getattr(person, 'sex'))
When running the program, the output is:
Gender is: Male AttributeError: 'Person' object has no attribute 'sex'
The named attribute 'sex' does not exist in the Person class. Therefore, when the getattr() method is called with the default value 'Male', it will return 'Male'.
However, if we do not provide any default values, an AttributeError statement will be raised when the named attribute 'sex' is not found, that is, the object does not have a 'sex' attribute.