我希望能够以字符串的形式获取变量的名称,但我不知道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(),所以我猜有一种方法。


当前回答

我一直很想这么做。这个技巧与rlotun的建议非常相似,但它是一行代码,对我来说很重要:

blah = 1
blah_name = [ k for k,v in locals().iteritems() if v is blah][0]

Python 3 +

blah = 1
blah_name = [ k for k,v in locals().items() if v is blah][0]

其他回答

>>> a = 1
>>> b = 1
>>> id(a)
34120408
>>> id(b)
34120408
>>> a is b
True
>>> id(a) == id(b)
True

通过这种方式,可以获得'a'或'b'的varname。

我发现如果你已经有了一个特定的值列表,那么@S描述的方式。抽签是最好的;然而,下面描述的方法可以很好地在整个代码中添加所有的变量和类,而不需要提供变量名,尽管如果你想要指定它们。可以扩展代码以排除类。

import types
import math  # mainly showing that you could import what you will before d

# Everything after this counts
d = dict(globals())

def kv_test(k,v):
    return (k not in d and 
            k not in ['d','args'] and
            type(v) is not types.FunctionType)

def magic_print(*args):
    if len(args) == 0: 
        return {k:v for k,v in globals().iteritems() if kv_test(k,v)}
    else:
        return {k:v for k,v in magic_print().iteritems() if k in args}

if __name__ == '__main__':
    foo = 1
    bar = 2
    baz = 3
    print magic_print()
    print magic_print('foo')
    print magic_print('foo','bar')

输出:

{'baz': 3, 'foo': 1, 'bar': 2}
{'foo': 1}
{'foo': 1, 'bar': 2}

在python3中,这很容易

myVariable = 5
for v in locals():
  if id(v) == id("myVariable"):
    print(v, locals()[v])

这将打印:

myVariable 5

我一直很想这么做。这个技巧与rlotun的建议非常相似,但它是一行代码,对我来说很重要:

blah = 1
blah_name = [ k for k,v in locals().iteritems() if v is blah][0]

Python 3 +

blah = 1
blah_name = [ k for k,v in locals().items() if v is blah][0]

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

为什么这么有必要呢?

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()工作。