stevenha对这个问题有一个很好的答案。但是,如果你真的不希望在命名空间字典闲逛,无论如何,你可以得到给定值的所有名字在这样的特定范围/命名空间:
def foo1():
x = 5
y = 4
z = x
print names_of1(x, locals())
def names_of1(var, callers_namespace):
return [name for (name, value) in callers_namespace.iteritems() if var is value]
foo1() # prints ['x', 'z']
如果你有一个Python工作它支持堆栈框架(大多数情况下,CPython都支持),但不要求您将本地代码转换为names_of
函数;该功能可以检索其调用者的框架本身词典:
def foo2():
xx = object()
yy = object()
zz = xx
print names_of2(xx)
def names_of2(var):
import inspect
callers_namespace = inspect.currentframe().f_back.f_locals
return [name for (name, value) in callers_namespace.iteritems() if var is value]
foo2() # ['xx', 'zz']
如果你使用,你可以在name属性分配一个值类型的工作,你可以给它一个名称,然后使用:
class SomeClass(object):
pass
obj = SomeClass()
obj.name = 'obj'
class NamedInt(int):
__slots__ = ['name']
x = NamedInt(321)
x.name = 'x'
最后,如果你带班工作属性和你想让他们知道他们的名字(描述是显而易见的使用情况),你可以做很酷的技巧与元类编程像他们这样做的Django的ORM和SQLAlchemy的声明式表格定义:
class AutonamingType(type):
def __init__(cls, name, bases, attrs):
for (attrname, attrvalue) in attrs.iteritems():
if getattr(attrvalue, '__autoname__', False):
attrvalue.name = attrname
super(AutonamingType,cls).__init__(name, bases, attrs)
class NamedDescriptor(object):
__autoname__ = True
name = None
def __get__(self, instance, instance_type):
return self.name
class Foo(object):
__metaclass__ = AutonamingType
bar = NamedDescriptor()
baaz = NamedDescriptor()
lilfoo = Foo()
print lilfoo.bar # prints 'bar'
print lilfoo.baaz # prints 'baaz'
你真的想要做什么?没有'x'没有调用,所以你可以使用print'var x =%s'%x,但是你不需要。为什么? – tuergeist 2009-11-03 07:53:22
重复:http://stackoverflow.com/questions/1534504/convert-variable-name-to-string – 2009-11-03 08:22:26
重复太http://stackoverflow.com/questions/592746/how-can-you-print-a-variable -name-in-python-closed – fortran 2009-11-03 11:14:07