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