[Python]标准库--inspect

inspect 模块


昨天在infoq上看到豆瓣架构师演讲有提到这个模块 今天找来文档看看
Doc:这样写到
The inspect module provides several useful functions to help get information about live objects such as modules, classes, methods, functions, tracebacks, frame objects, and code objects.

这个模块是针对模块,类,方法,功能等对象提供些有用的方法。例如可以帮助我们检查类的内容,检查方法的代码,提取和格式化方法的参数等。


 

#coding:utf8 



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 inspect.getsource(Test) #代码块 带缩进



#打印全局变量中的模块对象

myglobals = {}

myglobals.update(globals())

modules = [value

           for key, value in myglobals.items()

           if inspect.ismodule(value)]

print modules  



#查看类的可调用方法

for name, value in inspect.getmembers(Test, callable):

    print "    Callable:", name



for name, value in inspect.getmembers(Test(), callable):

    print "   Instance Callable:", name







def hello():

    print inspect.stack()[0][3]

    print inspect.stack()



hello()



具体项目中的用法还不了解。


 

 

你可能感兴趣的:(python)