zoukankan      html  css  js  c++  java
  • 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__方法,还是会出现递归的问题。
  • 相关阅读:
    398. Random Pick Index
    382. Linked List Random Node
    645. Set Mismatch
    174. Dungeon Game
    264. Ugly Number II
    115. Distinct Subsequences
    372. Super Pow
    LeetCode 242 有效的字母异位词
    LeetCode 78 子集
    LeetCode 404 左叶子之和
  • 原文地址:https://www.cnblogs.com/wangshuyang/p/8953063.html
Copyright © 2011-2022 走看看