我可以使具有相同值的不同变量指向不同的对象吗? [英] Can i make different variables of same values point to diffrent objects?
问题描述
我认为这个问题可能已经在SO上找到了答案,但我似乎找不到.如果找到答案,请将其标记为重复.
I think this question might already have an answer here on SO, but I can't seem to find it. Please mark it as duplicate if you find an answer.
我不是在问为什么,但是我怎么不能让这种事情发生呢?
我希望j
与i
具有不同的id
.
I want j
to have a diffrent id
than i
.
说我做什么,
>>> i = 6
>>> j = 6
>>> id(i)
10919584
>>> id(j)
10919584 #I don't want this, I want j to point to a different object
所以,我得到了上面代码中发生的事情(或者至少我认为是这样),但是我的问题是如何防止这种情况发生?
So, I get what happens in the code above(Or at least I think I do), but my question is how can I prevent it?
我只是出于好奇而问,它可能没有实际用途或相关性.
推荐答案
对此的可能用法有些奇怪;我找到的选项:
A bit weirded by the possible uses of this; the option I've found:
class NoFixedInt(int):
pass
a = NoFixedInt(6)
b = NoFixedInt(6)
c = NoFixedInt(6)
print id(a)
# 4485155368
print id(b)
# 4485155656
print id(c)
# 4485155728
当然,我不知道这是否对您有用,因为它存在您必须强制转换所有内容的问题,但确实可以解决问题.
Of course, I don't know if this works for you, as it has the issue that you have to cast everything, but it does the trick.
这篇关于我可以使具有相同值的不同变量指向不同的对象吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!