Python中关于getsourcelines函数输出结果的请教,感谢!
-- coding: utf-8 --
import inspect
import os
class Test(object):
“”“Test Class “””
def test(self):
self.fuc = lambda x:x
class Testone(Test):
pass
print( inspect.getsourcelines(Test)) #代码块,每行一个元素,组成数组
上面代码输出如下,请问数组中的 6 是表示什么?
([‘class Test(object):\n’, ‘\t""“Test Class “””\n’, ‘\tdef test(self):\n’, ‘\t\tself.fuc = lambda x:x\n’], 6)
Python中关于getsourcelines函数输出结果的请教,感谢!
2 回复
inspect.getsourcelines() 返回的是源码行号列表和源代码行列表,行号是实际文件中的起始行号。
比如你有这样一个文件 example.py:
# example.py 第1行
def foo():
print("hello")
print("world")
然后你在另一个脚本里:
import inspect
import example
lines, start_line = inspect.getsourcelines(example.foo)
print("起始行号:", start_line) # 输出 2(因为def foo():在文件第2行)
print("源代码:")
for i, line in enumerate(lines, start=start_line):
print(f"{i}: {line}", end="")
输出会是:
起始行号: 2
源代码:
2: def foo():
3: print("hello")
4: print("world")
注意行号是从 1 开始计数的文件实际行号,lines 里包含换行符。
如果你遇到行号和预期不符,检查一下是不是有装饰器、注释或者空行影响了定位。
总结:行号对应实际文件行,从1开始。
看文档啊

