Python built-in functions (25) -- getattr, pythongetattr
English document:
-
getattr
(
Object,
Name[,
Default])
-
Return the value of the named attribute
Object.
NameMust 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
x.foobar
. If the named attribute does not exist,
DefaultIs returned if provided, otherwise
AttributeError
Is raised.
-
Note:
-
-
1. The function is to obtain the attribute named name from the object, which is equivalent to calling object. name.
# 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 6> 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 "<pyshell #17>", line 1, in <module> getattr (s, 'age') AttributeError: 'stduent' object has no attribute 'age'