在python的官方文档中,getattr ()的说明如下:
Getattr(object,name[ (,default] ) ) ) )。
returnthevalueofthenamedattributeofobject.namemustbeastring.ifthestringisthenameoftheobject’sattributes、 theresultisthevalueofthatattribute.for example,getattr(x,' foobar ' ) isequivalenttox.foobar.ifthenamedatttributedoed
根据属性名称返回对象的值。 如果" name "是对象属性的名称,则返回相应属性的值。
' #--*coding:utf-8--*-'
__author__='cbdxl '
classattrtest(object ) : def _ init _ (self ) :通过
deftrygetattr0(self ) :
self.name='cbdxl '
print self.name # equalstoself.name
printgetattr(self,' name ' ) defattribute1) self,para1) : print ' attribute1called and ' para1' ispassedinasapaparamesapapararamed
deftrygetattr(self ) :
fun=getattr(self,' attribute1' (print type ) fun ) ) ) )。
fun(crown ) ) if_name_==) __main_':
test=attr test (打印' getattr ) self,'name' ) equalstoself.name ' test.try getattr0(打印' attribute1isindinde
此代码的结果如下:
Getattr(self,' name ' ) equals to self.name
cbdxl
cbdxl
attribute1isindirectlycalledbyfun (
属性1计算和复制
attrribute1 is directly called
attribute1calledandtomatoispassedinasaparameter
Process finished with exit code 0
第一个函数tryattribute0) )如定义所示可以非常好地理解。 第二个函数tryattribute1) )有点费解。 其实原理并不复杂。 您可以看到fun的类型是实例方法。 现在,请考虑getattr () )对函数的返回值是指针,指针将赋值给接收它的变量,然后call变量等于调用该变量所指向的函数。
我知道原理了。 getattr的作用是什么?
你知道java和c#的反射吗? 反射的一个重要作用是通过延迟加载来解除耦合,使系统能够更有效地运行。 作为动态语言,python显然在这方面更强大
getattr ) )是实现python反射的块,与其他方法(例如setattr )、dir )等组合,可以有很多有趣的地方。
让我们看看下一个场景。
1 .需要动态地将其他类中的方法添加到一个类中。
#如果a类有以下方法:
efaddnewattributesfromotherclass (self,class_name ) :
func_names=dir(class_name ) forfunc _ nameinfunc _ names : if not func _ name.starts with (_ ' ) 3360
new_func=getattr(class_name,func_name ) ) )。
self.__setattr__(func_name,new_func ) )
我们需要的是:
a=A () ) )。
b=B () ) )。
a.addnewattributesfromotherclass (b ) )。
现在,a可以调用b的“非专用”方法。