python之__setattr__常见问题

#__setattr__
class Foo(object):
    def set(self,k,v):
        pass
    def __setattr__(self, key, value):
        print(key,value)
        pass

obj = Foo()
obj.set('x',123)
obj.x = 123 #用__setattr__比set函数要方便许多

#__setattr__方法常见的坑

class Foo(object):
    def __init__(self):
        self.storage = {}
    def __setattr__(self, key, value):
        self.storage={'k1':'v1'}
        print(key,value)
    def __getattr__(self, item):
        print(item)


obj = Foo()
obj.x = 123
'''
当初始化的时候,self.storage,对象调用storage就会自动执行__setattr__方法,
然后__setattr__方法里面又是对象调用属性,就会再执行setattr,这样就是无限递归了。
为了避免这个问题需要用下面这种方式实现:
'''
class Foo(object):
    def __init__(self):
        object.__setattr__(self,'storage',{})

    def __setattr__(self, key, value):
        self.storage={'k1':'v1'}
        print(key,value)

    def __getattr__(self, item):
        print(item)
        return "sdf"
obj = Foo()
#注意如果obj.x = 123就会触发__setattr__方法,还是会出现递归的问题。

 

posted @ 2018-04-26 16:00  shuyang  阅读(3251)  评论(0编辑  收藏  举报