__getattr__()是仅当属性不能在实例的__dict__或它的类(类的__dict__),或父类其__dict__中找到时,才被调用。一般在代码中包含一个对getattr()內建函数的调用
一个包装类的例子:
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)
wcomplex = WrapMe(3.5+4.2j)
print wcomplex
print wcomplex.real
print wcomplex.imag,
print wcomplex.conjugate()
print wcomplex.get()
结果:
(3.5+4.2j)
3.5
4.2 (3.5-4.2j)
(3.5+4.2j)
__getattribute__()
若想要有一个能执行每一个属性的访问的函数,而不光是当属性不能在类和实例中找到的情况,则__getattribute__()能满足这个需求
它和__getattr__()的不同之处在于,当属性被访问时,它是一直都可以被调用的
一个包装类的例子:
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)
wcomplex = WrapMe(3.5+4.2j)
print wcomplex
print wcomplex.real
print wcomplex.imag,
print wcomplex.conjugate()
print wcomplex.get()
结果:
(3.5+4.2j)
3.5
4.2 (3.5-4.2j)
(3.5+4.2j)
__getattribute__()
若想要有一个能执行每一个属性的访问的函数,而不光是当属性不能在类和实例中找到的情况,则__getattribute__()能满足这个需求
它和__getattr__()的不同之处在于,当属性被访问时,它是一直都可以被调用的

浙公网安备 33010602011771号