简体   繁体   English

python 中的 __qualname__ 是什么?

[英]What is __qualname__ in python?

  • What is __qualname__ in python and how is it useful? __qualname__中的 __qualname__ 是什么,它有什么用处?

  • Why would I need to use it over __name__ ?为什么我需要在__name__上使用它?

I read the docs , but they didn't help me get a clear understanding on it's usefulness.我阅读了文档,但它们并没有帮助我清楚地了解它的用处。

I have read Get fully qualified name of a Python class (Python 3.3+) .我已阅读Get fully qualified name of a Python class (Python 3.3+)
That question asks "how to get a qualified name" , which presumes that one knows the meaning of "qualified name" .该问题询问“如何获得限定名” ,这假定人们知道“限定名”的含义。 Obviously, the answer to that question is to use the __qualname__ attribute.显然,该问题的答案是使用__qualname__属性。

My question asks what __qualname__ is, and why should I use it over __name__ .我的问题是__qualname__什么为什么我应该在__name__上使用它。

__qualname__ gives more complete information than __name__ and therefore can be more helpful in debugging, for example. __qualname__提供了比__name__更完整的信息,因此在调试时更有帮助。

Example:例子:

>>> 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__ is also adding some backwards compatibility with Python 2's .im_class . __qualname__还为 Python 2 的.im_class添加了一些向后兼容性。

More details in the rationale for PEP 3155 PEP 3155 的基本原理中的更多详细信息

Just to (potentially) add to the previous answer, __qualname__ can also be called from inside a class, without it having to be bound to any methods.只是为了(可能)添加到前面的答案,也可以从__qualname__内部调用 __qualname__,而不必绑定到任何方法。 This allows to get a class' name from inside the class when you don't have an __init__ method defined:当您没有定义__init__方法时,这允许从 class 内部获取类的名称:

class myClass:
    print(__qualname__)

This will return:这将返回:

myClass

A practical scenario where I found this useful is when working with logging .我发现这很有用的一个实际场景是使用logging If you want to implement it in a module with a class that, as stated before, doesn't have an __init__ method, ie consists only on class methods, then to add the class' name to the dot-notation path that logging requires to join logs generated by different modules into a single one, __qualname__ seems like an easy solution.如果您想在具有 class 的模块中实现它,如前所述,它没有__init__方法,即仅包含 class 方法,然后将类的名称添加到logging所需的点符号路径将不同模块生成的日志合并为一个, __qualname__似乎是一个简单的解决方案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM