python __setattr__表现得像__getattr__

时间:2015-11-24 13:58:32

标签: python dictionary

我有一个包含字典的类,我使用__getattr__(key)来更好地访问dictionary[key]现在我希望能够以相同的访问方式设置字典中的内容。< / p>

Class foo(object):
    def __init__(self, name):
        self.props = {"name":name}

    def __getattr__(self, attribute):
        return self.props[attribute]

这样我就可以通过这种方式访问​​它了

f = foo("test")
print f.name

我希望能够设置属性,但是使用 setattr 会因为在其他任何失败之前调用它而产生问题。有没有办法让它像 getattr 一样?

1 个答案:

答案 0 :(得分:1)

__setattr__没问题,但在设置__setattr__之前调用self.props时,您需要保护自己不被发现(RuntimeError: maximum recursion depth exceeded

class foo(object):
    # List of properties which are not stored in the props dict
    __slots__ = ('props', 'other_property')

    def __init__(self, name):
        self.props = {"name":name}
        self.other_property = 2

    def __getattr__(self, attribute):
        return self.props[attribute]

    def __setattr__(self, name, value):
        if name in self.__slots__:
            super(foo, self).__setattr__(name, value)
        else:
            self.props[name] = value

f = foo("name")
print f.name
f.value = 2
f.name = "TEST"
print f.value
print f.props
相关问题