setattr()和object .__ setattr __()有什么区别? [英] What's the difference between setattr() and object.__setattr__()?

查看:407
本文介绍了setattr()和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 (so x.__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屋!

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