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__方法,还是会出现递归的问题。

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM