[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()

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


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值