以声明方式__name__设置类



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

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

我想也许这只是在类定义块完成后被覆盖的情况。 但似乎这不是真的,因为这个名字是可写的,但显然没有在类字典中设置:

>>> 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(类定义块的内部和外部)?

Potato.__name__在哪里解决?

大多数记录的 dunder 方法和属性实际上存在于对象的本机代码端。在 CPython 的情况下,它们被设置为对象模型中定义的 C 结构槽中的指针。 (在这里定义 - https://github.com/python/cpython/blob/04e82934659487ecae76bf4a2db7f92c8dbe0d25/Include/object.h#L346 ,但是当一个人实际在 C 中创建新类时,字段更容易可视化,如下所示:https://github.com/python/cpython/blob/04e82934659487ecae76bf4a2db7f92c8dbe0d25/Objects/typeobject.c#L7778 ,其中定义了"超级"类型)

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

如何处理Potato.__name__= 其他(类定义块的内部和外部)?

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

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

类块中,所有属性和方法都被收集到一个普通字典中(尽管可以自定义)。此字典传递给type.__new__和其他元类方法 - 但如上所述,此方法从显式传递的name参数(即调用type.__new__时传递的 "name" 参数)填充__name__槽 - 即使它只是使用用作命名空间的字典中的所有名称更新类__dict__代理。

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

一个有趣的轶事是,三天前我遇到了一些代码,试图在类体中显式重用__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.范罗森)

它同样适用于尝试在类主体中定义__name__

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


如果真的想__name__重写为类体中的一个属性,那么元类就像元类一样简单

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

最新更新