简体   繁体   English

setattr()和object .__ setattr __()之间有什么区别?

[英]What's the difference between setattr() and object.__setattr__()?

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? 我知道你不能在没有从object继承的object上调用object.__setattr__ ,但是两者之间还有什么不同吗? I'm working in Python 2.6, if this matters. 我正在使用Python 2.6,如果这很重要的话。

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+). 再次阅读这个问题,我误解了@ paper.cut所提出的问题:经典类和新风格类之间的区别(不是Python 3+中的问题)。 I do not know the answer to that. 我不知道答案。


Original Answer * 原始答案*

setattr(instance, name, value) is syntactic sugar for instance.__setattr__(name, value) ** . setattr(instance, name, value)是语法糖, instance.__setattr__(name, value) **

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 . 你只需要在类定义中调用object.__setattr__(...) ,然后只有直接子类化object - 如果你是其他的子类,例如Spam ,那么你应该使用super()来获取heirarchy中的下一个项目,或者调用Spam.__setattr__(...) - 这样你就不会冒险丢失超类已经定义的行为,直接将它们跳过到object


* applies to Python 3.0+ classes and 2.x new-style classes *适用于Python 3.0+类和2.x新风格类


** There are two instances where setattr(x, ...) and x.__setattr__(...) are not the same: **有两个实例,其中setattr(x, ...)x.__setattr__(...)不相同:

  • x itself has a __setattr__ in it's private dictionary (so x.__dict__[__setattr__] = ... (this is almost certainly an error) x本身的私有字典中有一个__setattr__ x.__dict__[__setattr__] = ... (所以x.__dict__[__setattr__] = ... (这几乎肯定是一个错误)

  • x.__class__ has a __getattribute__ method -- because __getattribute__ intercepts every lookup, even when the method/attribute exists x.__class__有一个__getattribute__方法 - 因为__getattribute__拦截每个查找,即使方法/属性存在

NB These two caveats apply to every syntactic sugar shortcut: 注意这两个警告适用于每个语法糖快捷方式:

  • setattr
  • getattr
  • len
  • bool
  • hash
  • etc 等等

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM