object.__setattr__() 和直接设置有什么区别吗?
Is there any difference between object.__setattr__() and directly set?
在 werkzeug 中,我们看到:
class Local(object):
__slots__ = ('__storage__', '__ident_func__')
def __init__(self):
object.__setattr__(self, '__storage__', {})
所以,我可以用 self.__storage__ = {}
代替 object.__setattr__(self, '__storage__', {})
,为什么?
同样的class定义了一个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__
属性。
在 werkzeug 中,我们看到:
class Local(object):
__slots__ = ('__storage__', '__ident_func__')
def __init__(self):
object.__setattr__(self, '__storage__', {})
所以,我可以用 self.__storage__ = {}
代替 object.__setattr__(self, '__storage__', {})
,为什么?
同样的class定义了一个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__
属性。