在 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/