利用inspect函数可以获取类中的docs, 类名,类以及类的代码,是否存在的模块等等。
#! /usr/bin/env python
# -*- 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.ismodule(os)
print inspect.isclass(Test)
print inspect.getdoc(Test)
print inspect.getsourcefile(Test) #文件路径
print inspect.getsourcelines(Test) #代码块,每行一个元素,组成数组
print "-"*30
print inspect.getsource(Test) #代码块 带缩进
#
##打印全局变量中的模块对象
print "-"*30
myglobals = {}
myglobals.update(globals())
modules = [value
for key, value in myglobals.items()
if inspect.ismodule(value)]
print modules
#
print "*"*30
##查看类的可调用方法
for name, value in inspect.getmembers(Test, callable):
print " Callable:", name
for name, value in inspect.getmembers(Test(), callable):
print " Instance Callable:", name
print "="*30
def hello():
print inspect.stack()[0][3]
print inspect.stack()
hello()
以上代码是引用自网上某处代码,如果侵犯版权,请在下面留言,我会删掉或者自己修改一下。