在 Python 中检索对对象的引用列表 [英] Retrieving the list of references to an object in Python
问题描述
全部:
a = 1b = ac = b
现在我想获取一个标记了对象 1
的列表,即 [a, b, c]
.我怎么能这样做?
顺便说一句,如何在这里正式调用变量a"?到目前为止,我知道它是对象的对象标签",但我不知道它的术语是什么.
谢谢!
为什么我需要这个:
a = b = c = 1打印 a, b, c1 1 1一 = 2打印 a, b, c2 1 1
在C等其他语言中,如果我重新分配a = 2,a,b,c应该是2,但是在python中,没有像引用这样的东西,所以改变abc的所有值的唯一方法是据我所知,a = b = c = 2,这就是为什么要获取对象的所有引用.
你问的不是很实用,也不可能.这是一种疯狂的做法:
<预><代码>>>>一 = 1>>>b = a>>>c = b>>>当地人(){'a': 1, 'c': 1, 'b': 1, '__builtins__': <module '__builtin__' (builtin)>, '__package__': None, '__name__': '__main__', '__doc__': 无}>>>[key for key, value in locals().items() if value == 1]['a', 'c', 'b']>>>全局变量(){'a': 1, 'c': 1, 'b': 1, '__builtins__': <module '__builtin__' (builtin)>, '__package__': None, '__name__': '__main__', '__doc__': 无}>>>[key for key, value in globals().items() if value == 1]['a', 'c', 'b']All:
a = 1
b = a
c = b
Now I want to get a list of object 1
tagged, which is [a, b, c]
. How could I do this?
BTW, how to call variable "a" here officially? I know so far it is a "object tag" for the object, but I have no idea what is the term of it.
Thanks!
why do I need this:
a = b = c = 1
print a, b, c
1 1 1
a = 2
print a, b, c
2 1 1
in other language such as C, a,b,c should be 2 if I re-assign a = 2, but in python, there's no such thing like reference, so the only way to change all the value of a b c is a = b = c = 2 so far as I know, that is why purposed to get all reference of an object.
What you're asking isn't very practical and isn't possible. Here's one crazy way of doing it:
>>> a = 1
>>> b = a
>>> c = b
>>> locals()
{'a': 1, 'c': 1, 'b': 1, '__builtins__': <module '__builtin__' (built-in)>, '__package__': None, '__name__': '__main__', '__doc__': None}
>>> [key for key, value in locals().items() if value == 1]
['a', 'c', 'b']
>>> globals()
{'a': 1, 'c': 1, 'b': 1, '__builtins__': <module '__builtin__' (built-in)>, '__package__': None, '__name__': '__main__', '__doc__': None}
>>> [key for key, value in globals().items() if value == 1]
['a', 'c', 'b']
这篇关于在 Python 中检索对对象的引用列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!