以声明方式设置 class __name__

Setting a class __name__ declaratively

为什么不能以声明方式覆盖 class 名称,例如使用不是有效标识符的 class 名称?

>>> class Potato:
...     __name__ = 'not Potato'
...     
>>> Potato.__name__  # doesn't stick
'Potato'
>>> Potato().__name__  # .. but it's in the dict
'not Potato'

我认为这可能只是在 class 定义块完成后被覆盖的情况。但似乎这不是真的,因为这个名字是可写的,但显然 not 在 class 字典中设置:

>>> Potato.__name__ = 'no really, not Potato'
>>> Potato.__name__  # works
'no really, not Potato'
>>> Potato().__name__  # but instances resolve it somewhere else
'not Potato'
>>> Potato.__dict__
mappingproxy({'__module__': '__main__',
              '__name__': 'not Potato',  # <--- setattr didn't change that
              '__dict__': <attribute '__dict__' of 'no really, not Potato' objects>,
              '__weakref__': <attribute '__weakref__' of 'no really, not Potato' objects>,
              '__doc__': None})
>>> # the super proxy doesn't find it (unless it's intentionally hiding it..?)
>>> super(Potato).__name__
AttributeError: 'super' object has no attribute '__name__'

问题:

  1. Potato.__name__在哪里解析?
  2. 如何处理 Potato.__name__ = other(在 class 定义块的内部和外部)?

Where does Potato.__name__ resolve?

大多数记录在案的 dunder 方法和属性实际上存在于对象的本机代码端。在 CPython 的情况下,它们被设置为对象模型中定义的 C 结构中槽中的指针。 (此处定义 - https://github.com/python/cpython/blob/04e82934659487ecae76bf4a2db7f92c8dbe0d25/Include/object.h#L346 , but with fields easier to visualize when one actually creates a new class in C, like here: https://github.com/python/cpython/blob/04e82934659487ecae76bf4a2db7f92c8dbe0d25/Objects/typeobject.c#L7778 ,其中定义了 "super" 类型)

因此,__name__type.__new__ 中的代码设置,它是第一个参数。

How is Potato.__name__ = other handled (inside and outside of a class definition block)?

一个class的__dict__参数不是一个普通的字典——它是一个特殊的映射代理对象,原因正是[=65上的所有属性设置=] 本身不通过 __dict__,而是通过类型中的 __setattr__ 方法。在那里,对这些开槽的 dunder 方法的赋值实际上填充在 C 对象的 C 结构中,然后反映在 class.__dict__ 属性上。

因此, 之外 class 块,cls.__name__ 以这种方式设置 - 因为它发生在 class 之后已创建。

一个class块中,所有的属性和方法都被收集到一个普通的dict中(尽管可以定制)。这个 dict 被传递给 type.__new__ 和其他 metaclass 方法——但如上所述,这个方法从显式传递的 name 参数(即,在对 type.__new__) 的调用中传递的 "name" 参数 - 即使它只是更新 class __dict__ 代理,将 dict 中的所有名称用作命名空间。

这就是为什么 cls.__dict__["__name__"] 可以使用与 cls.__name__ 槽中不同的内容开始,但随后的分配使两者同步。

一个有趣的轶事是,三天前我发现一些代码试图在 class 主体中显式地重用 __dict__ 名称,这具有类似的令人费解的副作用。 我什至想知道是否应该有一个错误报告,并询问了 Python 开发人员 - 正如我所想的那样,权威的答案是:

...all __dunder__ names are reserved for the implementation and they should
only be used according to the documentation. So, indeed, it's not illegal,
but you are not guaranteed that anything works, either.

(G.范罗森)

它同样适用于尝试在 class 正文中定义 __name__

https://mail.python.org/pipermail/python-dev/2018-April/152689.html


如果一个人真的想覆盖 __name__ 作为 class 正文中的一个属性,metaclass 就像 metaclass 一样简单是:

class M(type):
    def __new__(metacls, name, bases, namespace, **kw):
         name = namespace.get("__name__", name)
         return super().__new__(metacls, name, bases, namespace, **kw)