In the official Python document: GetAttr () is explained as follows:
GetAttr (object, name[, default]) return the value of the
named attribute of object. Name must to be a string. If The string is the name of one of the object's attributes, the result is the value of. For example, GetAttr (x, ' Foobar ') are equivalent to X.foobar. If the named attribute does not exist, the default are returned if provided, otherwise attributeerror is raised.
Returns an object value based on the property name. If "name" is the name of an object property, the value of the corresponding property is returned.
' #-*-coding:utf-8-*-'
__author__ = ' Lucas '
class Attrtest (object):
def __init__ (self):
Pass def trygetattr0 (self):
self.name = ' Lucas '
print self.name
#equals to self.name
print getattr (self, ' Name '
def attribute1 (self,para1):
print ' attribute1 called and ' + para1+ ' is passed in as a parameter '
def Trygetattr (self):
fun = GetAttr (self, ' attribute1 ')
print type (fun)
fun (' crown ')
if __name__== ' __main__ ':
test = attrtest ()
print ' GetAttr (self,\ ' name\ ') equals to Self.name '
test.trygetattr0 ()
print ' attribute1 is indirectly called by Fun () '
test.trygetattr ()
print ' attrribute1 is directly Called '
test.attribute1 (' tomato ')
The result of this code execution is:
GetAttr (self, ' name ') equals to Self.name
Lucas
Lucas
Attribute1 are indirectly called by Fun ()
<type ' Instancemethod ' >
attribute1 called and crown are passed in as a parameter
attrribute1 are directly called
at Tribute1 called and tomato is passed into as a parameter
Process finished with exit code 0
The first function tryattribute0 () is very well understood, as the definition says. The second function, Tryattribute1 (), is a bit confusing. In fact, the principle is not complex, we see fun type is Instancemethod, here you can think: For a function, the return value of GetAttr () is a pointer, the pointer assigned to the variable to accept it, then call this variable is equal to the calling variable point to the function.
Principle we know, what is the role of the getattr?
Are you familiar with the reflection in Java or C #? One of the most important effects of reflection is delayed loading, which can be decoupled, allowing the system to run more efficiently. As a dynamic language, Python is clearly more powerful in this area,
GetAttr () is a building block for Python reflection, and with other methods such as SetAttr (), dir (), we can do a lot of interesting things.
Let's look at the following scenario:
1. I need to dynamically add some methods in a class to other classes:
#如果类A中有如下方法:
def addnewattributesfromotherclass (self,class_name):
func_names = Dir (class_name)
for Func_name in Func_names:
if not func_name.startswith ('_'):
new_func = GetAttr (class_name,func_name)
self . __setattr__ (Func_name,new_func ())
All we need to do is:
A = a ()
B = B ()
A.addnewattributesfromotherclass (b)
So that a can call the ' non Private ' method in B.