• [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()
    
    具体项目中的用法还不了解。
    


  • 相关阅读:
    Spring MVC的Controller统一异常处理:HandlerExceptionResolver
    Log4j按级别输出日志到不同文件配置
    Linux top命令用法
    free -m内存使用详解
    Linux运维中遇到的常见问题
    ubuntu16.04 nginx安装
    redis主从配置及主从切换
    Redis持久化配置-AOF
    如何处理消极想法
    libevent安装总结
  • 原文地址:https://www.cnblogs.com/javawebsoa/p/3093532.html
Copyright © 2020-2023  润新知