python中类中的代码行?

2024-09-29 01:39:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图找出类或函数中存储在python文件中的代码行数 我的代码是这样的。。。我想要的是找出a类中的代码行数而不是所有的文件。。。有什么好办法吗??在

import inspect
import foo    
for a,b in inspect.getmembers(foo):
    if inspect.isclass(b):
        print a  # find a class within the file

Tags: 文件函数代码inimportforiffoo
2条回答

您仍然可以使用inspect

In [6]: from test import A

In [7]: import inspect

In [8]: inspect.getsourcelines(A)
Out[8]: 
(['class A(object):\n',
  '    pass\n',
  '    pass\n',
  '    pass\n',
  '    pass\n',
  '    pass\n',
  '    pass\n',
  '    pass\n',
  '    pass\n'],
 1)

len(inspect.getsourcelines(A)[0])将返回您想要的。在

len(inspect.getsourcelines(a)[0])

从inspect.getsourcelines文件:

Return a list of source lines and starting line number for an object.

所以你需要0索引

相关问题 更多 >