English documents:
-
-
getattr
(
object,
name[,
default])
-
-
-
Return the value of the named attribute of
object.
name must is a string. The If the string is the name of the one of the object ' s attributes, and the result is the value of this attribute. For example, was
getattr(x, ‘foobar‘)
equivalent to
x.foobar
. If the named attribute does not exist, the
default is returned if provided, and otherwise is
AttributeError
raised.
-
-
-
-
-
-
Gets the property value of the object
-
-
Description
-
-
-
-
-
1. The function function is to get the property named name from Object objects, equivalent to calling Object.name.
#定义类Student >>> class Student: def __init__ (self,name): self.name = name >>> s = stduent ( ' Aim ') >>> getattr (S, ' name ') #等效于调用s. Name ' aim ' >>> s.name ' aim '
2. Function The third parameter of the default is an optional parameter, if the object in the meaning of the Name property, the value of the Name property is returned, if there is no Name property, the default value is returned, if default does not pass in the value, then an error.
#定义类Student >>> class Student: def __init__ (self,name): self.name = name>>> getattr (s, ' name ') #存在属性name ' Aim ' >>> getattr (S, ' age ', 6) #不存在属性age, but provided a default value that returns the default value 6>>> getattr (S, ' age ') #不存在属性age, Default value not provided, call error Traceback (most recent called last): File "<pyshell#17>", line 1, in <module> getattr (S, ' Age ') Attributeerror: ' Stduent ' object with no attribute ' age '
Python built-in function (--GETATTR)