如何获取python中变量的字符串表示形式? [英] How do I get the string representation of a variable in python?

查看:120
本文介绍了如何获取python中变量的字符串表示形式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在python中有一个变量x.我如何从变量中找到字符串"x".这是我的尝试:

I have a variable x in python. How can i find the string 'x' from the variable. Here is my attempt:

def var(v,c):
  for key in c.keys():
    if c[key] == v:
      return key


def f():
  x = '321'
  print 'Local var %s = %s'%(var(x,locals()),x)  

x = '123'
print 'Global var %s = %s'%(var(x,locals()),x)
f()

结果是:

Global var x = 123
Local var x = 321

上面的食谱似乎有点怪诞.有没有更好/更短的方法来达到相同的结果?

The above recipe seems a bit un-pythonesque. Is there a better/shorter way to achieve the same result?

推荐答案

问:我在python中有一个变量x.如何从变量中找到字符串"x".

Q: I have a variable x in python. How can i find the string 'x' from the variable.

A:如果我正确地理解了您的问题,那么您希望将变量的值更改为它的名称.在Python中这实际上是不可能的.

A: If I am understanding your question properly, you want to go from the value of a variable to its name. This is not really possible in Python.

在Python中,实际上没有变量"之类的东西. Python真正具有的是名称",可以将对象绑定到它们.可以绑定的名称(如果有)对对象没有影响.它可能绑定了几十个不同的名称,也可能没有.

In Python, there really isn't any such thing as a "variable". What Python really has are "names" which can have objects bound to them. It makes no difference to the object what names, if any, it might be bound to. It might be bound to dozens of different names, or none.

请考虑以下示例:

foo = 1
bar = foo
baz = foo

现在,假设您有一个值为1的整数对象,并且想向后工作并找到它的名称.你会打印什么?三个不同的名称将那个对象绑定到了它们,并且它们都同样有效.

Now, suppose you have the integer object with value 1, and you want to work backwards and find its name. What would you print? Three different names have that object bound to them, and all are equally valid.

print(bar is foo) # prints True
print(baz is foo) # prints True

在Python中,名称是一种访问对象的方法,因此无法直接使用名称.您也许可以在locals()中进行搜索以找到值并恢复名称,但这充其量只是一个绝招.在我上面的示例中,"foo","bar"和"baz"中的哪一个是正确"的答案?它们都指向完全相同的对象.

In Python, a name is a way to access an object, so there is no way to work with names directly. You might be able to search through locals() to find the value and recover a name, but that is at best a parlor trick. And in my above example, which of foo, bar, and baz is the "correct" answer? They all refer to exactly the same object.

P.S.上面是我之前写过的答案的经过部分编辑的版本.我想这次我在措辞上做得更好.

P.S. The above is a somewhat edited version of an answer I wrote before. I think I did a better job of wording things this time.

这篇关于如何获取python中变量的字符串表示形式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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