• Python标准库--inspect


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

    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))         # True
    print(inspect.isclass(Test))        # True
    print(inspect.getdoc(Test))         # Test Class
    
    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)
    
    输出结果:
    [<module 'builtins' (built-in)>, <module 'inspect' from 'D:\python\python\lib\inspect.py'>, <module 'os' from 'D:\python\python\lib\os.py'>]
    

     查看类和类对象有哪些方法可以调用 

    # 查看类的可调用方法
    for name, value in inspect.getmembers(Test, callable):
        print("    Callable:", name)
    
    for name, value in inspect.getmembers(Test(), callable):
        print(" Instance Callable:", name)

    获取栈的全部调用信息

    def debug():
        import inspect
        print(inspect.stack()[0][3])
        print(inspect.stack()[1][3])
        caller_name = inspect.stack()[1][3]
        # print("[DEBUG]: enter {}()".format(caller_name) )
    
    def say_hello():
        debug()
        # print("hello!")
    
    def say_goodbye():
        debug()
        # print("goodbye!")
    
    if __name__ == '__main__':
        say_hello()
        say_goodbye()
    
    运行结果:
    debug
    say_hello
    debug
    say_goodbye
    

      

    1. inspect.ismodule(object): 是否为模块

    2. inspect.isclass(object):是否为类

    3. inspect.ismethod(object):是否为方法(bound method written in python)

    4. inspect.isfunction(object):是否为函数(python function, including lambda expression)

    5. inspect.isgeneratorfunction(object):是否为python生成器函数

    6. inspect.isgenerator(object):是否为生成器

    7. inspect.istraceback(object): 是否为traceback

    8. inspect.isframe(object):是否为frame

    9. inspect.iscode(object):是否为code

    10. inspect.isbuiltin(object):是否为built-in函数或built-in方法

    11. inspect.isroutine(object):是否为用户自定义或者built-in函数或方法

    12. inspect.isabstract(object):是否为抽象基类

    13. inspect.ismethoddescriptor(object):是否为方法标识符

    14. inspect.isdatadescriptor(object):是否为数字标识符,数字标识符有__get__ 和__set__属性; 通常也有__name__和__doc__属性

    15. inspect.isgetsetdescriptor(object):是否为getset descriptor

    16. inspect.ismemberdescriptor(object):是否为member descriptor

      

     

  • 相关阅读:
    Flask基础01
    Django logging配置
    JSONP和CORS跨域
    Scrapy框架
    请求库之urllib,requests及工具selenium
    MongoDB安装
    Django 视图层
    Django REST framework 2
    WebSocket
    爬虫性能相关
  • 原文地址:https://www.cnblogs.com/feifeifeisir/p/10627854.html
Copyright © 2020-2023  润新知