Python 3没有显示更改的__name__属性的原因吗?

时间:2013-11-22 14:13:06

标签: python python-3.x

我不知道Python 3做了这样的改变。

Python 2.7.5 (default, May 15 2013, 22:44:16) [MSC v.1500 64 bit (AMD64)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> def f():
    pass

>>> f.__name__ = 'g'
>>> f
<function g at 0x000000000264C6D8>

在Python 3中:

Python 3.3.2 (v3.3.2:d047928ae3f6, May 16 2013, 00:06:53) [MSC v.1600 64 bit (AMD64)]   on win32
Type "copyright", "credits" or "license()" for more information.
>>> def f():
    pass

>>> f.__name__ = 'g'
>>> f
<function f at 0x0000000003335AE8>

这样做的原因是什么?我错过了什么吗?

1 个答案:

答案 0 :(得分:3)

改为使用__qualname__

>>> def f():
...     pass
...
>>> f.__qualname__ = 'g'
>>> f
<function g at 0x0000000002AE5C80>

根据PEP 3155 -- Qualified name for classes and functions - Proposal

  

修改了repr()str()个函数和类以供使用   __qualname__而不是__name__

另请参阅:What's New in Python 3.3 - PEP 3155: Qualified name for classes and functions