python - object.__setattr__() 和直接设置有什么区别吗?

标签 python flask werkzeug

在 werkzeug 中,我们看到:

class Local(object):
    __slots__ = ('__storage__', '__ident_func__')

    def __init__(self):
        object.__setattr__(self, '__storage__', {})

那么,我可以使用 self.__storage__ = {} 来替换 object.__setattr__(self, '__storage__', {}),为什么?

最佳答案

同一个类定义了custom __setattr__ method将值存储在 self.__storage__ :

def __setattr__(self, name, value):
    ident = self.__ident_func__()
    storage = self.__storage__
    try:
        storage[ident][name] = value
    except KeyError:
        storage[ident] = {name: value}

但是,您首先需要设置一个初始空字典,因此 object.__setattr__方法用于绕过自定义方法。

如果您要使用self.__storage__ = {}那么上面的自定义方法将被调用,这将导致属性错误,如 self.__storage__尚不存在。或者更确切地说,它会导致无限递归问题,如 custom __getattr__ method将反复调用来解决丢失的 __storage__属性。

关于python - object.__setattr__() 和直接设置有什么区别吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42457058/

相关文章:

python - 使用 Beautiful Soup 将多个类提取到 pandas 数据框中

python - 针对集合的 CRUD 操作的单一职责原则

flask - 使用 Eve 处理 html 请求

python - 使用 render_template 有条件地呈现 HTML 片段

python - flask.request.form 中的动态表单字段

javascript - 在 Werkzeug 异常上设置标题

python - Flask 测试客户端使用方法获取错误的 View 函数

python - 返回动态创建的函数

python - 未知的字符问题�

python - curl 形式的 http post 方法的默认 header 内容类型是什么?