python - 如何在 python 中获取完整的类型名称?

标签 python

type()的打印结果在 Python 中,有时会显示不在当前范围内的类型名称。例如,以下代码将显示 "<type 'frame'>"

import inspect
a = inspect.currentframe()
print( type( a ) )

但是没有frame输入当前范围!如果我尝试在交互式解释器中使用它,我会得到一个错误:

>>> frame
NameError: name 'frame' is not defined

那么有什么办法可以得到像“inspect.something.frame”这样的“完全限定”类型名称,以便我可以在我的代码中引用它?

更新

不幸的是,__module__也不起作用:

>>> type( a ).__module__
'__builtin__'

最佳答案

"What's in a name? That which we call a frame 
 By any other name would smell as sweet."

如果您正在寻找对应于框架类型的 Python 对象,您可以使用:

In [38]: import types

In [39]: types.FrameType
Out[39]: <type 'frame'>

当然,这只是type(a)的另一种写法:

In [42]: import inspect

In [43]: a = inspect.currentframe()

In [44]: types.FrameType == type(a)
Out[44]: True

如果您查看 types 模块,您会发现 types.FrameType 是这样定义的:

try:
    raise TypeError
except TypeError:
    tb = sys.exc_info()[2]
    TracebackType = type(tb)
    FrameType = type(tb.tb_frame)
    del tb

他们所做的只是找到一个 frame 的实例,并将 FrameType 定义为该实例的 type

这基本上就是你在定义时所做的事情

MyFrameType = type(a)

所以结论是:要获得实例的类型,只需调用type(obj)。您不需要事先知道任何其他信息。

关于python - 如何在 python 中获取完整的类型名称?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15165101/

相关文章:

python - 如何解决 django 中的 'module' 对象不可迭代

Python 脚本通过双击和 IDLE 运行,但不通过 Windows CMD shell 运行

python - 错误 - 没有名为 '_pywrap_tensorflow' 的模块

python - 为什么 '#!/usr/bin/env python' 据说比 '#!/usr/bin/python' 更正确?

python - 创建等距数组列表的优雅方法

python - 如何绘制遮挡/重叠物体的轮廓?

python - 有没有简单的方法可以在Python类构造函数中指定参数的默认值而不需要编写继承?

python - 比较不同大小的二维数组

python - 在 python 日期时间中处理月份

python - Windows 解释器上未定义命名元组