python - 以声明方式设置类 __name__

标签 python metaclass python-datamodel python-descriptors python-object

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

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

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

>>> 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 是如何处理的(在类定义 block 的内部和外部)?

最佳答案

Where does Potato.__name__ resolve?

大多数记录在案的 dunder 方法和属性实际上存在于对象的 native 代码端。在 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,其中定义了“ super ”类型)

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

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

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

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

一个类 block 中,所有属性和方法都被收集到一个普通的字典中(尽管可以自定义)。这个字典被传递给 type.__new__ 和其他元类方法——但是如上所述,这个方法从显式传递的 name 中填充 __name__ 槽> 参数(即在调用 type.__new__ 时传递的“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)

关于python - 以声明方式设置类 __name__,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49781234/

相关文章:

Python 正则表达式 - Unicode 文本匹配的位置和值

python - 条形图与散点图的颜色相同

Qt ENUMS - setProperty 隐式转换

python - 动态添加属性到 Django 模型

python - 你如何检查一个python方法是否被绑定(bind)?

python - Python中的元类是什么?

Python:我有一个单词列表,想要检查这些单词在文件中每一行中出现的次数

Python:重命名父类(super class)的方法及其函数范围引用

Python:重新定义了原始 'object' 类。如何取回 'object' 类?

python - Python/Numpy 中的正规方程实现