wim*_*wim 6 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'
Run Code Online (Sandbox Code Playgroud)
我想也许这只是在类定义块完成后被覆盖的情况.但似乎这不是真的,因为名称是可写的,但显然没有在类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__'
Run Code Online (Sandbox Code Playgroud)
问题:
Potato.__name__解决?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__= other如何处理(在类定义块内部和外部)?
一个类的__dict__参数不是一个普通的字典——它是一个特殊的映射代理对象,其原因正是为了使类本身的所有属性设置不通过__dict__,而是通过__setattr__类型中的方法。在那里,对这些槽式 dunder 方法的赋值实际上填充在 C 对象的 C 结构中,然后反映在class.__dict__属性上。
因此,在类块之外,cls.__name__以这种方式设置 - 因为它发生在类创建之后。
在一个类块中,所有属性和方法都被收集到一个普通的 dict 中(尽管可以自定义)。这个 dict 被传递给type.__new__和其他元类方法 - 但如上所述,这个方法__name__从显式传递的name参数(即在调用中传递的“名称”参数type.__new__)填充插槽- 即使它只是更新类 __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.
Run Code Online (Sandbox Code Playgroud)
(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)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
586 次 |
| 最近记录: |