python学习笔记2-获取参数的名字

本文深入探讨了Python中函数参数的处理,通过`locals()`方法展示了函数内部变量的字典表示,并利用`inspect`模块获取函数参数名称。示例代码展示了如何在函数调用中获取和打印参数名及值,对于理解Python函数内部工作原理有帮助。
摘要由CSDN通过智能技术生成

m="monday"
s="sunday"
def foo(**kws):
    loc = locals()#把locals()方法
    print(loc)
    print(kws) # 这样试试
    for i in kws:
        print(i,"=",kws[i])
foo(s=s)
print("********************")


# 现在的打印效果some code <class 'str'> monday
# 希望的打印效果 t <class 'str'> monday

import inspect
def foo2(s):
    arg_name = [n for n, v in inspect.currentframe().f_back.f_locals.items()
                if v is s][0]
    print(f'{arg_name} -> {s}')

foo2(m)
foo2(s)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值