python--inspect

本文详细介绍了Python中Inspect模块的使用方法,Inspect模块能够帮助开发者收集Python对象的各种信息,如源代码、参数详情等。文章通过具体示例展示了如何使用Inspect模块获取类或函数的源码,以及如何解析堆栈和进行类型检查。

  给大家介绍下用的比较少的模块--Inspect

inspect模块用于收集python对象的信息,可以获取类或函数的参数的信息,源码,解析堆栈,对对象进行类型检查等等

import hello
import inspect

print(inspect.getsource(hello))

def h():
    print 'hello'

def hm(m,k):
    print m,k

class w(object):
    def __init__(a,self):
        name = a
    def g(self):
        print name,'hello world'

特定的方法调用

#返回对象的源代码
>>> inspect.getsource(hello.w)
"class w(object):\n    def __init__(a,self):\n"
"name = a\n    def g(self):\n        print name,'hello world'\n"

#方便的获取__init__的**参数
>>> inspect.getargspec(hello.w.__init__)
ArgSpec(args=['a', 'self'], varargs=None, keywords=None, defaults=None)

可以通过help()方法获取该使用函数的文本

>>> help(inspect.getsourcefile)
Help on function getsourcefile in module inspect:

getsourcefile(object)
    Return the filename that can be used to locate an object's source.
    Return None if no way can be identified to get the source.
    
>>> help(inspect.getmembers)
Help on function getmembers in module inspect:

getmembers(object, predicate=None)
    Return all members of an object as (name, value) pairs sorted by name.
    Optionally, only return members that satisfy a given predicate.

>>> help(inspect.stack)
Help on function stack in module inspect:

stack(context=1)
    Return a list of records for the stack above the caller's frame.

 

转载于:https://www.cnblogs.com/eilinge/p/9705367.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值