getattr 基本概念
getattr提供了一种通过方法名来获取方法的一种途径,python官方的解释如下:
getattr ( object , name [, default ] )Return the value of the namedattribute of object.namemust be a string. If the string is the name of one of the object’sattributes, the result is the value of that attribute. For example,getattr(x,'foobar') isequivalent to x.foobar.If the named attribute does not exist, defaultis returned if provided, otherwise AttributeErroris raised.
其中需要注意的一点是, name必须是字符串。 通过下面的例子来说明 getattr的使用。
class GetattrTest(object):
def __init__(self,nm):
self.name = nm
def display(self):
return self.name
gat = GetattrTest('john')
print getattr(gat, 'name','default')
print getattr(gat, 'age','default')
print getattr(gat,'display','default')
print getattr(gat,'display','default')()
输出:
john
default
<boundmethod GetattrTest.display of <__main__.GetattrTest object at 0x7f0b26847b50>>
john
如果有name属性则打印出name的值。类中没有age属性,所以打印出default。
getattr 在包装里面的使用
在Python2.2以前,是不允许从标准类型进行派生的。因此可以用包装的方法实现类似的效果。如下:
class WrapMe(object):
def __init__(self, obj):
self.__data = obj
def get(self):
return self.__data
def __repr__(self):
return 'self.__data'
def __str__(self):
return str(self.__data)
def __getattr__(self, attr):
return getattr(self.__data, attr)
wrappedComplex = WrapMe(3.5+4.2j)
print wrappedComplex
print(wrappedComplex.real)
print(wrappedComplex.imag)
print(wrappedComplex.conjugate())
print(wrappedComplex.get())
输出:
(3.5+4.2j)
3.5
4.2
(3.5-4.2j)
(3.5+4.2j)
print(wrappedComplex):调用__repr__()方法。
wrappedComplex.real:当前类中没有real概述性。这块实现的核心方法是,在实例或在字典中搜寻real改属性,如果找不到,就调用__getattr__方法,方法中调用getattr方法,获取实例的real方法,即(3.5+4.2j).real=3.5。
其他的属性和方法调用也类似。