python __setattr__ 的行为类似于 __getattr__

标签 python dictionary

我有一个包含字典的类,我使用 __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__ 没问题,但是您需要保护自己免受在设置 self.props 之前调用 __setattr__ 的情况(运行时错误:超出最大递归深度)

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

关于python __setattr__ 的行为类似于 __getattr__,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33895581/

相关文章:

java - 多维 map

python - 如何在 Python Kivy 的 TextInput 字段中显示希伯来语文本

python - 你如何在 pytest session 结束时清理资源?

python - Flask,使用不同的数据库连接、相同的模型多次注册相同的蓝图

python - 重申列表和字典

python - 将字典列表转换为字典字典的优雅方法

c++ - 定义一个内部有结构的 map

c++ - 在循环中使用新指针填充 map (C++)

python - 在 Pydev 中设置交互式 session 的最大 RAM 使用率

python - 如何在python中拆分匹配模式的字符串