getattr的基本概念
getattr提供了一种从方法名称中获取方法的方法。 python的公式说明如下。
getattr
(请参阅
对象
因为,
名字
[,
默认
]。
) )
returnthevalueofthenamedattributeofobject.namemustbeastring.ifthestringisthenameoftheobject’sattributes、 theresultisthevalueofthatattribute.for example,getattr(x,' foobar ' ) isequivalenttox.foobar.ifthenamedatttributedoed
其中需要注意的是,
name必须是字符串。
用以下例子说明
使用getattr。
classgetattrtest(object ) :
def __init__(self,nm ) :
self.name=nm
efdisplay(self ) :
return self.name
gat=getattrtest('John ' ) )。
打印获取器(gat,' name ',' default ' ) )。
打印获取器(gat,' age ',' default ' ) )。
打印获取器(gat,' display ',' default ' ) )。
打印获取器(gat,' display ',' default ' ) ) ) ) ) ) )。
输出:
约翰
默认
约翰
如果有name属性,则打印name的值。 类没有age属性,因此打印default。
getattr在软件包中的应用
在Python2.2之前,不允许从标准型派生。 因此,可以用包装的方法实现同样的效果。 如下所示。
classwrapme (对象) :
def __init__(self,obj ) :
self.__data=obj
默认(self ) :
返回self._ _ data
def __repr__(self ) :
返回' self._ _ data '
def __str__(self ) :
返回str (self._ _ data ) )。
def __getattr__(self,attr ) :
返回getattr (self._ _ data,attr ) )。
wrappedcomplex=wrapme(3.5 ) 4.2j ) ) )。
打印快速合成
打印(wrapped complex.real ) )。
打印(wrapped complex.imag ) )。
打印(wrapped complex.conjugate ()
打印(wrapped complex.get ) )
输出:
(3.5 ) 4.2j )。
3.5
4.2
(3.5-4.2j ) )。
(3.5 ) 4.2j )。
调用print (wrapped complex:_ _ repr _ _ ) )方法。
wrappedComplex.real :当前类没有real的概要。 此实现的主要方法是在实例或词典中搜索real以修改属性,如果找不到,则调用__getattr__方法,然后在该方法中调用getattr方法以获取实例的real方法(3.5 4.2j ).real=3.5。
其他属性和方法调用也是如此。