Python-inspect的使用

inspect模块提供了几个有用的函数来帮助获取有关于活动对象的信息,如模块、类、方法、函数、回溯、框架对象和代码对象。例如,它可以帮助您检查类的内容、检索方法的源代码、提取和格式化函数的参数列表,或者获得显示详细回溯所需的所有信息。下面来看一下inspect模块中一些常用的方法:

类型方法

getmodulename(path)

getmodulename根据路径获取模块名称

import os
from inspect import getmodulename

path = os.path.join(os.getcwd(), "inspect.py")
name = getmodulename(path)
print(name, type(name))             # inspect_1 <class 'str'>

name = getmodulename(os.getcwd())
print(name)                         # None

ismodule(object)

ismodule判断对象是否是模块

import os
from inspect import ismodule

class Student(object):
    def __init__(self):
        self.name = "laozhang"
        self.age = 20


print(ismodule(os))  # True
print(ismodule(Student()))  # False

isclass(object)

isclass判断对象是否是个类

from inspect import isclass

class Student(object):

    def __init__(self):
        self.name = "laozhang"
        self.age = 20

print(isclass(Student))     # True
print(isclass(Student()))   # False

ismethod(object)

ismethod判断对象是否是个方法

from inspect import ismethod

class Student(object):
    def __init__(self):
        self.name = "laozhang"
        self.age = 20

    def say(self):
        print("hello world!")


s = Student()
print(ismethod(s.say))   # True
print(ismethod(s.name))  # False

isfunction(object)

isfunction判断对象是否是个函数,包括匿名函数,不包括内置函数

from inspect import isfunction

class Student(object):
    def __init__(self):
        self.name = "laozhang"
        self.age = 20

    def say(self):
        print("hello world!")

def
  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值