TL; DR:由于名称绑定在 Python 中的工作方式,您通常can't获取传递给函数的变量的名称。一些Python对象do有一个 name 属性,但这与您在赋值语句中绑定到对象的名称不同。
您的代码在打印时给您提供了误导性信息id
s。你实际上并没有打印id
s 的对象,您正在打印id
中名称字符串的 slocals()
dict
.
另外,当你得到locals()
在函数内部,它向您显示函数本地的内容。因此,要获取有关函数外部的本地对象的信息,您需要让函数访问实际的对象locals()
听写你感兴趣的内容。
下面是代码的修改版本,修复了id
的东西,还传递了一份副本locals()
数据到addr_type
功能。
请注意,当您调用该函数时a
or c
它打印两个名字的信息。
我还添加了几行内容来展示您如何can使用其打印函数的名称__name__
属性。请注意,当我们打印时new_name.__name__
它只是打印addr_type
,因为这是函数的值__name__
属性,事实上我们也将它绑定到new_name
是无关紧要的。
#!/usr/bin/env python
def addr_type(context, obj):
for k, v in context:
# if id(v) == id(a):
if v is obj:
print "k: %s" % k
print "v: %s" % v
print "a: %s" % hex(id(v))
print
print 15 * "-"
a = b = c = 10
b = 11
for k, v in list(locals().iteritems()):
if k.startswith('__'):
continue
print "k: %s" % k
print "v: %s" % v
print "a: %s" % hex(id(v))
print "##############"
print
if a is b:
print "a and b is the same objects"
else:
print "a and b is NOT the same objects"
if a is c:
print "a and c is the same objects"
else:
print "a and c is NOT the same objects"
if b is c:
print "b and c is the same objects"
else:
print "b and c is NOT the same objects"
print
context = list(locals().iteritems())
addr_type(context, a)
addr_type(context, b)
addr_type(context, c)
new_name = addr_type
print 'Function names =', addr_type.__name__, new_name.__name__
output
k: a
v: 10
a: 0x8dafd24
##############
k: c
v: 10
a: 0x8dafd24
##############
k: b
v: 11
a: 0x8dafd18
##############
k: addr_type
v: <function addr_type at 0xb748e17c>
a: 0xb748e17cL
##############
a and b is NOT the same objects
a and c is the same objects
b and c is NOT the same objects
k: a
v: 10
a: 0x8dafd24
k: c
v: 10
a: 0x8dafd24
---------------
k: b
v: 11
a: 0x8dafd18
---------------
k: a
v: 10
a: 0x8dafd24
k: c
v: 10
a: 0x8dafd24
---------------
Function names = addr_type addr_type
您可能会发现研究这篇优秀文章很有帮助关于 Python 名称和值的事实和神话,由 Stack Overflow 资深人士 Ned Batchelder 撰写。
Update
这是一个简单的函数,show
,它会打印您传递给它的名称,以及您传递给它的字典中该名称的值。通过传递它locals()
字典这允许它在本地范围内按名称查找对象。在函数内部,这是函数的局部变量。在函数之外,这就是所有全局变量。
def show(*args, names):
for s in args:
print(s, names.get(s, 'Not found!'))
def test(t):
a = 1
b = 2
c = 3
show('a', 'b', 'c', 't', names=locals())
test(42)
output
a 1
b 2
c 3
t 42