python - python 中的 __qualname__ 是什么?

标签 python python-3.x

  • Python 中的 __qualname__ 是什么以及它有什么用处?

  • 为什么我需要使用它而不是 __name__

我读了docs ,但它们并没有帮助我清楚地了解它的用处。

我已阅读Get fully qualified name of a Python class (Python 3.3+) .
该问题询问“如何获得限定名称”,假设人们知道“限定名称”的含义。显然,这个问题的答案是使用 __qualname__ 属性。

我的问题是问什么__qualname__是什么,以及为什么我应该使用它而不是__name__

最佳答案

__qualname__ 提供比 __name__ 更完整的信息,因此在调试等方面更有帮助。

示例:

>>> def f(): pass
... class A:
...    def f(self): pass
...    class A:
...        def f(self): pass
...
>>> # __name__ is not showing the path, so these functions look equal
>>> f.__name__
'f'
>>> A.f.__name__
'f'
>>> A.A.f.__name__
'f'
>>> # And these classes looks equal
>>> A.__name__
'A'
>>> A.A.__name__
'A'
>>>
>>> # __qualname__ shows the path, so these functions are distinguishable
>>> f.__qualname__
'f'
>>> A.f.__qualname__
'A.f'
>>> A.A.f.__qualname__
'A.A.f'
>>> # And these classes are distinguishable
>>> A.__qualname__
'A'
>>> A.A.__qualname__
'A.A'

__qualname__ 还添加了与 Python 2 的 .im_class 的一些向后兼容性。

More details in the rationale for PEP 3155

关于python - python 中的 __qualname__ 是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58108488/

相关文章:

python - 使用 Django bulk_create() 函数时,'dict' 对象没有属性 'pk'

python - 将值列表添加到现有字典列表(性能关键)

Python file.tell 给出了错误的值位置

python - Pandas.read_csv "unexpected end of data"错误

python-3.x - 通过点和线计算 CV2 单应性

python - 如何计算循环中python列表中字典的数量?

python - 一个关于C3的例子

django - 在 Django 1.7、Python3 中,使用 Floppyforms 1.3,不断出现错误 "TypeError: object() takes no parameters"

python - 从requirements.txt中安装轮子

mysql - 从 Drupal 7 迁移数据