【发布时间】: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__'
问题:
-
Potato.__name__在哪里解析? -
Potato.__name__ = other是如何处理的(在类定义块的内部和外部)?
【问题讨论】:
-
啊。并且在类定义期间设置它不起作用,因为它不会调用元类上的描述符(没有“点”)。
-
这感觉很像《镜花水月》中的名称与所谓的讨论。 en.m.wikipedia.org/wiki/Haddocks'_Eyes
标签: python metaclass python-datamodel python-descriptors python-object