我是一名美术师,一般来说是 python/编码的新手,并且在阅读本文档时也遇到了困难。 https://docs.python.org/2/library/inspect.html#
我正在尝试了解如何使用 inspect 模块。 此文件称为 TestClassA.py:
import inspect
class TestClassA(object):
def __init__(self):
print "this is crazy!"
print inspect.isclass(TestClassA)
#result is True
我想做的是返回 TestClassA 和其中的所有内容。基本概念是复制我的代码并将其作为消息弹出
print inspect.getsource(TestClassA)
结果是:
TypeError: <module '__main__' (built-in)> is a built-in class
但这很有趣。如果我使用:
print inspect.isclass(TestClassA)
结果为真。
所以我的最终目标是将特定类型的类复制到文本中(提醒:多个类可以在一个 .py 文件下)并将该特定类型的类放入另一个 .py 文件中。
谁能帮帮我?如果任何人也可以使用上面相同的简单示例设置示例,说明 inspect.getsourcefile 和 inspect.getsourcelines 如何工作,我将不胜感激。
请您参考如下方法:
import inspect
class TestClassA:
def __init__(self):
print "Hello"
print inspect.getsource(TestClassA)
在 pycharm 中为我工作,如果你想在交互模式下使用它,运行这个
import os
import inspect
inspect.getsource(os)
你提到的两个方法做同样的事情只是返回类型不同 检查https://docs.python.org/2/library/inspect.html#inspect.getsourcelines
