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__方法,仍是會出現遞歸的問題。
相關文章
相關標籤/搜索