【问题标题】:Setting a class __name__ declaratively以声明方式设置类 __name__
【发布时间】:2018-09-21 16:51:41
【问题描述】:

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

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

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

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

【问题讨论】:

  • 啊。并且在类定义期间设置它不起作用,因为它不会调用元类上的描述符(没有“点”)。
  • 这感觉很像《镜花水月》中的名称与所谓的讨论。 en.m.wikipedia.org/wiki/Haddocks'_Eyes

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


【解决方案1】:

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

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

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

类块中,所有属性和方法都被收集到一个普通的字典中(尽管可以自定义)。这个dict被传递给type.__new__和其他元类方法——但是如上所述,这个方法从显式传递的name参数中填充__name__槽(即在调用@ 987654336@)- 即使它只是使用字典中用作命名空间的所有名称来更新 __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)

【讨论】:

    猜你喜欢
    • 2014-07-29
    • 2011-08-29
    • 1970-01-01
    • 2023-03-17
    • 1970-01-01
    • 1970-01-01
    • 2014-09-13
    • 2014-11-15
    相关资源
    最近更新 更多