获取python变量的名称 [英] Get the name of a python variable

查看:53
本文介绍了获取python变量的名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

def f(s)打印<姓名>= s

鉴于变量 hello 的值为 10,我希望为 f(hello) 输出hello=10".

问题是如何获取变量的变量名,即?

这是为了调试目的.假设给定一个新语句 s=2

f(s) 在新语句之前会打印 s=0 如果 s 初始为 0,f(s) 在新语句之后会打印 s=2.

我可以轻松写:

def f(name,value)打印 "%s=%s"%(name,str(value))

并将其用作f("s",s),但这需要我输入两个参数,这样比较麻烦.

解决方案

我不确定这是否真的值得,但是使用来自框架的信息进行带有位置参数的简单函数调用,您可以执行以下操作:

>

导入检查定义你好(s1,s2,s3,s4):args = inspect.getargspec(hello).argsline = inspect.getouterframes(inspect.currentframe())[1][4][0]actual_args = map(str.strip, line[line.index('(')+1: line.index(')')].split(','))对于 zip(args, actual_args) 中的 x, y:打印{} 的值为 {}".format(y, locals()[x])a, b, c, d = 1, 2, 3, 4你好(a,b,c,d)

输出:

a 的值为 1b 的值为 2c 的值为 3d 的值为 4

def f(s)
  print <name of s> = s

I wish to output "hello=10" for f(hello), given that the variable hello has value 10.

The problem is how to get the variable name of the variable, i.e., <name of s>?

This is for debugging purpose. Say given a new statement s=2

f(s) before the new statement will print s=0 if s is initially 0, f(s) after the new statement will print s=2.

I can easily write:

def f(name,value)
   print "%s=%s"%(name,str(value))

and use it as f("s",s), but that would need me to input two arguments, which is more cumbersome.

解决方案

I am not sure if it is actually worth it, but using the information from frames for simple function calls with positional arguments you can do something like this:

import inspect

def hello(s1, s2, s3, s4):
    args = inspect.getargspec(hello).args
    line = inspect.getouterframes(inspect.currentframe())[1][4][0]
    actual_args = map(str.strip, line[line.index('(')+1: line.index(')')].split(','))
    for x, y in zip(args, actual_args):
        print "value of {} is {}".format(y, locals()[x])

a, b, c, d = 1, 2, 3, 4
hello(a, b, c, d)

output:

value of a is 1
value of b is 2
value of c is 3
value of d is 4

这篇关于获取python变量的名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆