【发布时间】:2015-07-11 14:44:39
【问题描述】:
我最初的目标是创建一个函数来打印给定对象的类型和内存地址。为了尽可能通用,我还希望包含变量名,如下所示:
>>> a=10
>>> print type_addr(a)
a: int, 0x13b8080
为此,我需要知道传递给此函数的变量的名称。这个page 建议以下代码(它有点修改版本,但想法保持不变,迭代locals().iteritems()。我知道它不安全,它在给定链接上提到了几个陷阱,但我的计划是改进它) :
#!/usr/bin/python
a = b = c = 10
b = 11
for k, v in list(locals().iteritems()):
if v is b:
# if id(v) == id(b):
print "k: %s" % k
print "v: %s" % v
print "a: %s" % hex(id(k))
以上代码的输出为:
k: b
v: 11
a: 0x7fece0f305f8
我的下一个目标是制作子程序,它会给我想要的结果,所以我尝试将它包装到子程序中:
#!/usr/bin/python
a = b = c = 10
b = 11
def addr_type(obj):
for k, v in list(locals().iteritems()):
# if id(v) == id(a):
if v is obj:
print "k: %s" % k
print "v: %s" % v
print "a: %s" % hex(id(k))
for k, v in list(locals().iteritems()):
if v is b:
# if id(v) == id(b):
print "k: %s" % k
print "v: %s" % v
print "a: %s" % hex(id(k))
print "#################"
addr_type(b)
上面代码的输出是:
k: b
v: 11
a: 0x7fc9253715f8
#################
k: obj
v: 11
a: 0x7fc9253198a0
如您所见,变量的名称和地址都不相同。然后我开始深入挖掘并尝试以下操作:
#!/usr/bin/python
a = b = c = 10
b = 11
for k, v in list(locals().iteritems()):
print "k: %s" % k
print "v: %s" % v
print "a: %s" % hex(id(k))
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"
返回:
k: a
v: 10
a: 0x7ff07d54b5d0
##############
k: c
v: 10
a: 0x7ff07d54bbe8
##############
k: b
v: 11
a: 0x7ff07d54b5f8
##############
<Some loaded modules here but nothing interesting>
##############
a and b is NOT the same objects
a and c is the same objects
b and c is NOT the same objects
问题:
- 如何重写工作代码并制作将打印传递变量名称的函数?
- 为什么相同的对象有不同的地址?
【问题讨论】:
标签: python