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