如何通过该模块的python'对象'获取模块源代码?
class TestClass(object):
def __init__(self):
pass
def testMethod(self):
print 'abc'
return 'abc'
众所周知
print inspect.getsource(TestClass)
可用于获取'TestClass'的源代码。
然而,
的结果ob = TestClass()
print inspect.getsource(ob)
如下所示,与预期不符。
Traceback (most recent call last):
File "D:\Workspaces\WS1\SomeProject\src\python\utils\ModuleUtils.py", line 154, in <module>
print inspect.getsource(ob)
File "C:\SciSoft\WinPython-64bit-2.7.10.3\python-2.7.10.amd64\lib\inspect.py", line 701, in getsource
lines, lnum = getsourcelines(object)
File "C:\SciSoft\WinPython-64bit-2.7.10.3\python-2.7.10.amd64\lib\inspect.py", line 690, in getsourcelines
lines, lnum = findsource(object)
File "C:\SciSoft\WinPython-64bit-2.7.10.3\python-2.7.10.amd64\lib\inspect.py", line 526, in findsource
file = getfile(object)
File "C:\SciSoft\WinPython-64bit-2.7.10.3\python-2.7.10.amd64\lib\inspect.py", line 420, in getfile
'function, traceback, frame, or code object'.format(object))
TypeError: <utils.TestClass.TestClass object at 0x0000000003C337B8> is not a module, class, method, function, traceback, frame, or code object
问题是:
如果上面有像'ob'这样的对象,如何通过一个以'ob'本身作为参数的方法检查ob的模块源代码或'TestClass'?
简而言之,实施以下模块
def getSource(obj):
###returns the result which is exactly identical to inspect.getsource(TestClass)
ob = TestClass()
###prints the result which is exactly identical to inspect.getsource(TestClass)
print getSource(ob)
(像这样的方法的场景比inspect.getsource()更常见;例如,检查未知的,未标记的对象的源代码。)
答案 0 :(得分:3)
实例没有源代码。
使用:
print inspect.getsource(type(ob))
或:
print inspect.getsource(ob.__class__)