我希望能够以字符串的形式获取变量的名称,但我不知道Python是否有那么多的自省功能。喜欢的东西:

>>> print(my_var.__name__)
'my_var'

我想这样做是因为我有一堆变量,我想把它们转换成一个字典,比如:

bar = True
foo = False
>>> my_dict = dict(bar=bar, foo=foo)
>>> print my_dict 
{'foo': False, 'bar': True}

但我想要更自动的。

Python有locals()和vars(),所以我猜有一种方法。


当前回答

在阅读这篇文章时,我看到了很多可怕的摩擦。给予很容易 一个糟糕的答案,然后让别人给出正确的答案。总之,这是我的发现。

来自:[effbot.org] (http://effbot.org/zone/python-objects.htm#names)

名称有点不同——它们不是对象的真正属性,对象本身也不知道它叫什么。

对象可以有任意数量的名称,也可以没有名称。

名称存在于名称空间中(例如模块名称空间、实例名称空间、函数的本地名称空间)。

注意:它说对象本身不知道它叫什么,所以这是线索。Python对象不是自引用的。然后它说,名称存在于名称空间中。我们在TCL/TK中有这个。所以也许我的回答会有所帮助(但它确实帮助了我)


    jj = 123
    print eval("'" + str(id(jj)) + "'")
    print dir()

166707048 ['__builtins__', '__doc__', '__file__', '__name__', '__package__', 'jj'] So there is 'jj' at the end of the list. Rewrite the code as: jj = 123 print eval("'" + str(id(jj)) + "'") for x in dir(): print id(eval(x)) 161922920 ['__builtins__', '__doc__', '__file__', '__name__', '__package__', 'jj'] 3077447796 136515736 3077408320 3077656800 136515736 161922920 This nasty bit of code id's the name of variable/object/whatever-you-pedantics-call-it. So, there it is. The memory address of 'jj' is the same when we look for it directly, as when we do the dictionary look up in global name space. I'm sure you can make a function to do this. Just remember which namespace your variable/object/wypci is in. QED.

其他回答

这在Python中是不可能的,因为Python真的没有“变量”。Python有名称,同一个对象可以有多个名称。

好吧,几天前我遇到了同样的需求,必须获得一个指向对象本身的变量名。

为什么这么有必要呢?

In short I was building a plug-in for Maya. The core plug-in was built using C++ but the GUI is drawn through Python(as its not processor intensive). Since I, as yet, don't know how to return multiple values from the plug-in except the default MStatus, therefore to update a dictionary in Python I had to pass the the name of the variable, pointing to the object implementing the GUI and which contained the dictionary itself, to the plug-in and then use the MGlobal::executePythonCommand() to update the dictionary from the global scope of Maya.

为了做到这一点,我所做的是:

import time

class foo(bar):

    def __init__(self):
        super(foo, self).__init__()
        self.time = time.time() #almost guaranteed to be unique on a single computer

    def name(self):
        g = globals()
        for x in g:
            if isinstance(g[x], type(self)):
                if g[x].time == self.time:
                    return x
                    #or you could:
                    #return filter(None,[x if g[x].time == self.time else None for x in g if isinstance(g[x], type(self))])
                    #and return all keys pointing to object itself

我知道这不是一个完美的解决方案,在全局许多键可以指向同一个对象,例如:

a = foo()
b = a
b.name()
>>>b
or
>>>a

而且这种方法不是线程安全的。如果我错了,请指正。

至少这种方法解决了我的问题,它在全局作用域中获取指向对象本身的任何变量的名称,并将其作为参数传递给插件,供它在内部使用。

我在int(原始整数类)上尝试了这一点,但问题是这些原始类不会被绕过(请纠正使用的技术术语,如果它是错误的)。你可以重新实现int,然后执行int = foo,但a = 3永远不会是foo的对象,而是原语的对象。为了克服这个问题,你必须使用a = foo(3)来让a.name()工作。

应该得到列表然后返回

def get_var_name(**kwargs):
    """get variable name
        get_var_name(var = var)
    Returns:
        [str] -- var name
    """
    return list(kwargs.keys())[0]

我根据这个问题的答案写了一个简洁有用的函数。我把它放在这里,以防有用。

def what(obj, callingLocals=locals()):
    """
    quick function to print name of input and value. 
    If not for the default-Valued callingLocals, the function would always
    get the name as "obj", which is not what I want.    
    """
    for k, v in list(callingLocals.items()):
         if v is obj:
            name = k
    print(name, "=", obj)

用法:

>> a = 4
>> what(a)
a = 4
>>|

在阅读这篇文章时,我看到了很多可怕的摩擦。给予很容易 一个糟糕的答案,然后让别人给出正确的答案。总之,这是我的发现。

来自:[effbot.org] (http://effbot.org/zone/python-objects.htm#names)

名称有点不同——它们不是对象的真正属性,对象本身也不知道它叫什么。

对象可以有任意数量的名称,也可以没有名称。

名称存在于名称空间中(例如模块名称空间、实例名称空间、函数的本地名称空间)。

注意:它说对象本身不知道它叫什么,所以这是线索。Python对象不是自引用的。然后它说,名称存在于名称空间中。我们在TCL/TK中有这个。所以也许我的回答会有所帮助(但它确实帮助了我)


    jj = 123
    print eval("'" + str(id(jj)) + "'")
    print dir()

166707048 ['__builtins__', '__doc__', '__file__', '__name__', '__package__', 'jj'] So there is 'jj' at the end of the list. Rewrite the code as: jj = 123 print eval("'" + str(id(jj)) + "'") for x in dir(): print id(eval(x)) 161922920 ['__builtins__', '__doc__', '__file__', '__name__', '__package__', 'jj'] 3077447796 136515736 3077408320 3077656800 136515736 161922920 This nasty bit of code id's the name of variable/object/whatever-you-pedantics-call-it. So, there it is. The memory address of 'jj' is the same when we look for it directly, as when we do the dictionary look up in global name space. I'm sure you can make a function to do this. Just remember which namespace your variable/object/wypci is in. QED.