This article describes the detailed description of the Python built-in getattr function in English:
Getattr (object, name [, default])
Return the value of the named attribute of object. name must be a string. if the string is the name of one of the object's attributes, the result is the value of that attribute. for example, getattr (x, 'foobar') is equivalent to x. foobar. if the named attribute does not exist, default is returned if provided, otherwise AttributeError is raised.
Note:
# Define class Student >>> class Student: def _ init _ (self, name): self. name = name >>> s = Stduent ('aim ') >>> getattr (s, 'name') # It is equivalent to calling s. name 'aim '> s. name 'aim'
2. the default parameter of the third function is an optional parameter. if the object contains the name attribute, the value of the name attribute is returned. if the name attribute is not present, the default value is returned. if the default parameter is not input, an error is returned.
# Define class Student >>> class Student: def _ init _ (self, name): self. name = name >>> getattr (s, 'name') # property name'aim '>>> getattr (s, 'age', 6) # property age does not exist, however, the default value is provided. the default value >>> getattr (s, 'age') is returned. # The Property age does not exist. if the default value is not provided, Traceback (most recent call last) is returned. File"
", Line 1, in
Getattr (s, 'age') AttributeError: 'stduent' object has no attribute 'age'
The above is a detailed description of the Python built-in getattr function. For more information, see other related articles in the first PHP community!