Py&禅

博客园 首页 新随笔 联系 订阅 管理
__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__()的不同之处在于,当属性被访问时,它是一直都可以被调用的


posted on 2010-05-24 19:46  Py&禅  阅读(1900)  评论(0)    收藏  举报