python - 'class object' 使用 `.__name__` 打印其名称,尽管没有 `__name__` 属性

标签 python

<分区>

Class_object 的名称可以通过.__name__ 访问, 查看代码:

>>> object
<class 'object'>
>>> object.__name__
'object'

尽管如此,__name__ 方法 不是 class_object 的默认设置中。

代码:

>>> foo = dir(object)
>>> foo
['__class__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__']
>>> foo.count('__name__')
0    # '__name__' is not in list

对象是所有类的基础。它具有对所有 Python 类实例通用的方法。

__name__ 的设置在哪里?

最佳答案

类体执行后Python会自动填充一些属性。这包括 __name__,还包括 __doc____qualname__(Python 3.4+)和 __module__。这些自动化属性的完整列表可作为 table in the inspect module documentation 获得:

Type    Attribute       Description
class   __doc__         documentation string
        __name__        name with which this class was defined
        __qualname__    qualified name
        __module__      name of module in which this class was defined

这些由 Python 类的基本元类定义:type(另请参阅 @Szabolcs answer)。

>>> '__name__' in dir(object.__class__)
True

关于python - 'class object' 使用 `.__name__` 打印其名称,尽管没有 `__name__` 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45633973/

相关文章:

c++ - 如何将 C++ 对象转换为 PyObject?

python - 使用 Python 自动从 ASPX 网站下载文件

python - 如何保证使用python asyncio发送的tcp数据?

python - 找到在 Robinhood 上获取比特币价格的 api 调用

Python装饰器多次调用函数

python - 使用 SqlAlchemy 将数据保存到数据库中,对象不可下标

python - 如何从 Python 中的 API 响应解析 JSON 数据?

python - Subprocess.call 或 Subprocess.Popen 不能使用 PATH (Linux/Windows) 中的可执行文件

python - 如何从接口(interface)获取物理接口(interface) IP 地址

python - 分数不完整