调用Python的超级(super)描述符协议。

huangapple go评论52阅读模式
英文:

Invocation of Python's descriptor protocol from super

问题

在Python的描述符指南中写道:

> 像super(A, obj).m这样的点查找会在obj.__class__.__mro__中搜索A之后紧接着的基类B,然后返回B.__dict__['m'].__get__(obj, A)。如果不是描述符,将返回m未更改的。

这似乎暗示属性m的搜索仅发生在类B__dict__中,而类B是紧随A之后的基类,但我认为它应该在A之后的MRO中的所有基类中进行。我有遗漏什么吗?

英文:

In the Python Descriptor HowTo guide, it is written that:

> A dotted lookup such as super(A, obj).m searches obj.__class__.__mro__
> for the base class B immediately following A and then returns
> B.__dict__['m'].__get__(obj, A). If not a descriptor, m is returned
> unchanged.

This seems to suggest that the search for attribute m only happens in the __dict__ of class B, which is the base class immediately following A, however, I think it should happen in all of the base classes in the mro following A. Am I missing anything here?

答案1

得分: 1

查找基本上是通常的算法,但省略了一些开始的步骤:

  1. type(m)的MRO中查找m,从A之后的类开始。

一旦找到了m,然后Python会检查m是否是描述符。如果是,将调用m.__get__,其返回值将是结果。否则,m本身就是结果。

英文:

The lookup is basically the usual algorithm, but with a couple of beginning steps skipped:

  1. <strike>Look for m in obj.__dict__.</strike>
  2. <strike>Look for m in type(m).__dict__.</strike>
  3. Look for m in a class in the MRO of type(m), starting with the class after A.

Once m is found, then Python checks if m is a descriptor. If it is, m.__get__ is called and its return value is the result. Otherwise, m itself is the result.

huangapple
  • 本文由 发表于 2023年5月28日 06:57:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/76349340.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定