Help on built-in function getattr in module __builtin__:
GetAttr (...)
GetAttr (object, name[, default]), value
Get A named attribute from an object; GetAttr (x, ' Y ') is equivalent to x.y.
When a default argument is given, it's returned when the attribute doesn ' t
Exist Without it, an exception was raised in the case.
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, GetAttr (x, ' Foobar ') are equivalent to X.foobar. If the named attribute does not exist, the default is returned if provided, and otherwise attributeerror is raised.
English Description:
Implement the reflection mechanism, you can get the method instance through the string.
This function implements the property that gets the object, which is represented by name, and is the string of the property name.
The parameter default is an optional parameter that returns this value when the property of the Get object does not exist, and does not throw an exception attributeerror if this parameter is not provided and is not found in the object properties.
Class A:
def __init__ (self):
SELF.A = ' a '
Def method (self):
Print "Method print"
A = A ()
Print GetAttr (A, ' a ', ' default ') #如果有属性a则打印a, otherwise printing default
A
Print GetAttr (A, ' B ', ' Default ') #如果有属性b则打印b, otherwise the default
Default
Print GetAttr (A, ' method ', ' Default ') #如果有方法method, otherwise printing its address, otherwise printing default
<bound method A.method of <__main__. A instance at 0x7f7d5204b8c0>>
Print GetAttr (A, ' method ', ' Default ') () #如果有方法method, run the function and print none otherwise printing default
Method Print
None
>>> class Foo:
... def __init__ (self):
... self.x=100
...
>>> Foo=foo ()
>>> Print (GetAttr (foo, ' X '))
100
>>> Print (foo.x)
100
>>> Print (GetAttr (foo, ' Y ', 200))
200
This article is from the "Big Cloud Technology" blog, please be sure to keep this source http://hdlptz.blog.51cto.com/12553181/1900157
Python built-in function 5-getattr ()