[英]python __setattr__ to act like __getattr__
我有一个包含字典的类,我使用__getattr__(key)
可以更好地访问dictionary[key]
现在我希望能够以相同的访问样式设置字典中的内容。
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一样工作?
__setattr__
很好,但是当设置__setattr__
之前调用self.props
时,您需要保护自己免受情况__setattr__
( 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.