inspect模块详解【持续更新】

inspect模块简介

inspect是Python标准库中的一个模块,提供了一些有用的函数,用于获取有关Python对象(如函数、类、模块等)的信息。使用inspect模块可以轻松地在Python中编写反射程序。

inspect模块方法

isfunction方法

inspect.isfunction(object):检查对象是否是函数

import inspect

def test_func():
    print("函数运行成功")

test_result = inspect.isfunction(test_func)

print(test_result)

> True

返回值为bool类型

ismodule方法

inspect.ismodule(object):检查对象是否是模块

import inspect

test_result = inspect.ismodule(inspect)

print(test_result)

> True

返回值为bool类型

isclass方法

inspect.isclass(object):检查对象是否是类

import inspect

class TestClass:
    test = True

test_result = inspect.isclass(TestClass)

print(test_result)

> True

返回值为bool类型

getmembers方法

inspect.getmembers(object[, predicate]):返回对象的成员列表。用于获取对象的成员信息。它返回一个包含所有成员名称和成员值的元组列表。你可以选择性地通过 predicate 参数过滤这些成员

import inspect

class MyClass:
    def __init__(self, value):
        self.value = value
    
    def method(self):
        return self.value

    @staticmethod
    def static_method():
        return "static method"

    @classmethod
    def class_method(cls):
        return "class method"
    
test_result = inspect.getmembers(MyClass)

print(type(test_result))

> <class 'list'>

for name, value in test_result:
    print(f"{name}: {value}")

返回值为list类型

Output:

  • 通过getmembers检查的类的相应信息
# 仅展示部分
__class__: <class 'type'>
__delattr__: <slot wrapper '__delattr__' of 'object' objects>
__dict__: {'__module__': '__main__', '__init__': <function MyClass.__init__ at 0x1049ce4c0>, 'method': <function MyClass.method at 0x104b5a670>, 'static_method': <staticmethod object at 0x1049b6fd0>, 'class_method': <classmethod object at 0x1049b6fa0>, '__dict__': <attribute '__dict__' of 'MyClass' objects>, '__weakref__': <attribute '__weakref__' of 'MyClass' objects>, '__doc__': None}
__dir__: <method '__dir__' of 'object' objects>
__doc__: None
...
使用 predicate 参数
获取所有方法
methods = inspect.getmembers(MyClass, predicate=inspect.isfunction)

for name, method in methods:
    print(f"{name}: {method}")
  • 这个代码只会打印 MyClass 中的所有方法,不包括属性
获取所有静态方法
static_methods = inspect.getmembers(MyClass, predicate=staticmethod)

for name, method in static_methods:
    print(f"{name}: {method}")
获取所有类方法
class_methods = inspect.getmembers(MyClass, predicate=classmethod)

for name, method in class_methods:
    print(f"{name}: {method}")

getargspec方法

inspect.getargspec(func):返回函数的参数列表和默认值

import inspect

def example_function(a, b, c=10, *args, **kwargs):
    pass

argspec = inspect.getargspec(example_function)

print(argspec)

> (a, b, c=10, *args, **kwargs)

查看参数列表和默认值

for param in test_result.parameters.values():
    print(param.name, param.default, param.annotation)

>	a <class 'inspect._empty'> <class 'inspect._empty'>
>	b <class 'inspect._empty'> <class 'inspect._empty'>
>	c 10 <class 'inspect._empty'>
>	args <class 'inspect._empty'> <class 'inspect._empty'>
>	kwargs <class 'inspect._empty'> <class 'inspect._empty'>

getsource方法

inspect.getsource(object):返回对象的源代码。

import inspect

test_result = inspect.getsource(inspect)

print(test_result)

输出不进行展示

getfile方法

inspect.getfile(object):返回对象所在的文件名。

import inspect

test_result = inspect.getfile(inspect)

print(test_result)

> /Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/inspect.py

getdoc方法

inspect.getdoc(object):返回对象的文档字符串

import inspect

test_result = inspect.getdoc(inspect)

print(test_result)

将返回inspect的文档说明

# 仅展示部分
Get useful information from live Python objects.

This module encapsulates the interface provided by the internal special
attributes (co_*, im_*, tb_*, etc.) in a friendlier fashion.
It also provides some help for examining source code and class layout.

Here are some of the useful functions provided by this module:
...

getmodule方法

inspect.getmodule(object):返回对象所在的模块

import inspect

test_result = inspect.getmodule(inspect.getmodule)

print(test_result)

> <module 'inspect' from '/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/inspect.py'>

signature方法

inspect.signature(func):返回函数的参数签名。

import inspect

def example_func(a, b: int, c: str = 'default', *args, **kwargs):
    pass

# 获取函数的签名
sig = inspect.signature(example_func)

# 打印签名
print(sig)

> (a, b: int, c: str = 'default', *args, **kwargs)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值