`object.__setattr__(self, ..., ...)` 而不是 `setattr(self, ..., ...)`? [英] `object.__setattr__(self, ..., ...)` instead of `setattr(self, ..., ...)`?

查看:60
本文介绍了`object.__setattr__(self, ..., ...)` 而不是 `setattr(self, ..., ...)`?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下是 werkzeug 库中 Local 类的 __init__ 方法:

Following is the __init__ method of the Local class from the werkzeug library:

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

我不明白这段代码的两件事:

I don't understand two things about this code:

  1. 他们为什么写

  1. Why did they write

object.__setattr__(self, '__storage__', {})

而不仅仅是

`setattr(self, '__storage__', {})`

  • 如果可以简单地写,他们为什么还要使用 __setattr__

    self.__storage__ = {}
    

  • 推荐答案

    这确保使用 __setattr__ 的默认 Python 定义.如果类已覆盖 __setattr__ 以执行非标准行为,但您仍希望访问原始 __setattr__ 行为,则通常使用它.

    This ensures that the default Python definition of __setattr__ is used. It's generally used if the class has overridden __setattr__ to perform non-standard behaviour, but you still wish to access the original __setattr__ behaviour.

    对于werkzeug,如果您查看Local 类,您会看到__setattr__ 的定义如下:

    In the case of werkzeug, if you look at the Local class you'll see __setattr__ is defined like this:

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

    不是在对象的字典中设置属性,而是在之前初始化的 __storage__ 字典中设置它们.为了完全设置 __storage__ 属性(以便以后可以像 self.__storage__ 一样访问它),__setattr__ 的原始定义来自必须使用对象,这就是为什么在构造函数中使用笨拙的符号.

    Instead of setting attributes in the dictionary of the object, it sets them in the __storage__ dictionary that was initialized previously. In order to set the __storage__ attribute at all (so that it may be accessed like self.__storage__ later), the original definition of __setattr__ from object must be used, which is why the awkward notation is used in the constructor.

    这篇关于`object.__setattr__(self, ..., ...)` 而不是 `setattr(self, ..., ...)`?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆