You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python函数内获取自身参数的传入值与默认值?

解决方案

以下是满足需求的完整实现代码:

import inspect

def func(a='my', b='dog', c='chews', d='bones'):
    # 动态获取当前函数对象,替代硬编码的'func'
    frame = inspect.currentframe()
    current_func = frame.f_globals[frame.f_code.co_name]
    
    # 获取函数签名与当前参数值
    sig = inspect.signature(current_func)
    current_args = locals()
    
    # 生成参数显示字符串
    param_list = []
    for name, param in sig.parameters.items():
        current_val = current_args[name]
        if current_val != param.default:
            param_list.append(f"{name}={repr(current_val)}")
        else:
            param_list.append(f"{name}={repr(param.default)}")
    
    params_str = f"({', '.join(param_list)})"
    print(f"Current parameters: {params_str}")
    
    return ' '.join([a, b, c, d])

# 测试调用
print('Statement #2: ' + func(a='her', b='cat', c='drinks', d='milk'))
print('Statement #3: ' + func(a='his', d='toys'))

关键实现细节

  1. 动态获取当前函数对象
    通过inspect.currentframe()获取当前执行的栈帧,再从栈帧的全局命名空间中根据函数名取出函数对象,彻底避免硬编码函数名。

  2. 参数值与默认值对比

    • 用inspect.signature()提取函数的参数元数据(包括默认值)
    • 用locals()获取函数内部当前的所有参数实际值
    • 遍历每个参数,对比实际值与默认值,按需拼接显示内容

运行效果

  • 全参数传入时,输出:
    Current parameters: (a='her', b='cat', c='drinks', d='milk')
    Statement #2: her cat drinks milk
    
  • 部分参数传入时,未指定的参数显示默认值:
    Current parameters: (a='his', b='dog', c='chews', d='toys')
    Statement #3: his dog chews toys
    

核心知识点

  • inspect.signature():解析函数签名,获取参数的默认值等定义信息
  • locals():返回当前作用域的局部变量字典,函数内调用时即为传入的参数集合
  • inspect.currentframe():获取当前执行栈帧,用于动态定位当前函数对象

内容的提问来源于stack exchange,提问作者Marc B. Hankin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.07 11:52:33