Python获取函数的参数的用途及实现方法(参数内省/Bob框架/inspect.signature)


# 一: 函数内省是什么
"""
    函数内省的例子: --->HTTP 微框架Bob,
                        简单说明:
                            路由知道你这个接口需要什么参数

"""
import bobo
@bobo.query('/')
def hello(person):
    return "hello %s" % person
"""
操作步骤:
    1-启动该文件:
        bobo -f 文件名.py
    2-访问
        http://localhost:8080  
        出现错误:  missing form variable person
    3-添加参数
        http://localhost:8080?person=xiaoxiao
        hello  小小
"""


# 二: 实现Bob框架检测参数的功能
"""
    inspect模块下,signature方法创建出一个Signature对象,-->下面的sig_func

            Signature对象有一个bind 方法(参数是一个方法名), ---->功能: 把任意个参数绑定到func中的形参上---->  用途: --->框架用来调用函数前验证参数

"""
import inspect
def func(name, age, **gender):
    pass

sig_func = inspect.signature(func)
my_para = {"name": "小王", "age": "20", "gender": "man", "type": "A"}

bound_para = sig_func.bind(**my_para)
print(bound_para)

# 删除一个元素(模拟少传参数)
del my_para["name"]
bound_para_2 = sig_func.bind(**my_para)
print(bound_para_2)         # TypeError: missing a required argument: 'name'


# 三: 手动获取参数的方法:
class AcsClient:

    def __init__(
            self,
            ak=None,
            secret=None,
            region_id="cn-hangzhou",
            auto_retry=True,
            max_retry_time=None,
            user_agent=None,
            port=80,
            timeout=None,
            public_key_id=None,
            private_key=None,
            session_period=3600,
            credential=None,
            debug=False):
        a = 1
        b = 2
        c = 3
        print(a+b+c)

# 方法1:
print(AcsClient.__init__.__code__.co_argcount)  # 查看参数的个数, 值为14
print(AcsClient.__init__.__code__.co_varnames)  # 查看所有的参数名以及 方法中定义的变量, 此处返回一个17元素的元组,前14个为参数, 后3个是方法中定义的变量
print(AcsClient.__init__.__defaults__)          # 查看参数的默认值

# 方法2:
print(help(AcsClient.__init__))

# 函数中参数的5种分类

发布了73 篇原创文章 · 获赞 14 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/qq_42327755/article/details/103635440