0
如何通過該模塊的python'object'獲取模塊源代碼?如何通過該模塊的python「對象」獲取模塊源代碼? (not inspect.getsource)
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」,如何檢查作業的模塊的源代碼,或「的TestClass」的對象,經由採用「OB」本身的方法作爲參數?
總之,實施以下模塊
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()更常見,例如,檢查一個未知的,拆封對象的源代碼)
非常感謝。我不知道這樣一個簡單的方法'類型' – Tom