setattr()和object .__ setattr __()有什么区别? [英] What's the difference between setattr() and object.__setattr__()?
问题描述
我知道您不能在不是从object
继承的对象上调用object.__setattr__
,但是两者之间还有其他不同吗?如果这很重要,我正在使用Python 2.6.
I know that you can't call object.__setattr__
on objects not inherited from object
, but is there anything else that is different between the two? I'm working in Python 2.6, if this matters.
推荐答案
再次阅读此问题,我误解了@ paper.cut在问什么:经典类和新型类之间的区别(在Python 3+中不是问题) ).我不知道答案.
Reading this question again I misunderstood what @paper.cut was asking about: the difference between classic classes and new-style classes (not an issue in Python 3+). I do not know the answer to that.
setattr(instance, name, value)
是instance.__setattr__(name, value)
** 的语法糖.
您只需要在类定义内调用object.__setattr__(...)
,然后仅在直接子类化object
时才调用-如果您在子类化其他内容(例如,Spam
),则应该使用super()
获取层次结构中的下一个项目,或调用Spam.__setattr__(...)
-这样,您就不必冒险将超类直接跳过到object
来忽略超类定义的行为.
You would only need to call object.__setattr__(...)
inside a class definition, and then only if directly subclassing object
-- if you were subclassing something else, Spam
for example, then you should either use super()
to get the next item in the heirarchy, or call Spam.__setattr__(...)
-- this way you don't risk missing behavior that super-classes have defined by skipping over them directly to object
.
* 适用于Python 3.0+类和2.x新型类
* applies to Python 3.0+ classes and 2.x new-style classes
** 在两个实例中,setattr(x, ...)
和x.__setattr__(...)
不同:
**There are two instances where setattr(x, ...)
and x.__setattr__(...)
are not the same:
-
x
本身在专用字典中有一个__setattr__
(所以x.__dict__[__setattr__] = ...
(这几乎肯定是一个错误)
x
itself has a__setattr__
in it's private dictionary (sox.__dict__[__setattr__] = ...
(this is almost certainly an error)
x.__class__
具有__getattribute__
方法-因为__getattribute__
拦截每查找,即使该方法/属性存在
x.__class__
has a __getattribute__
method -- because __getattribute__
intercepts every lookup, even when the method/attribute exists
NB 这两个警告适用于每个语法糖快捷方式:
NB These two caveats apply to every syntactic sugar shortcut:
-
setattr
-
getattr
-
len
-
bool
-
hash
- 等
setattr
getattr
len
bool
hash
- etc
这篇关于setattr()和object .__ setattr __()有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!