Can i make different variables of same values point to diffrent objects?

只谈情不闲聊 提交于 2019-12-10 17:48:50

问题


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.

I am not asking why, but how can I not let this happen?

I want j to have a diffrent id than i.

Say when i do,

>>> 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?

I am asking it just out of curiosity, it may or may not have any practical usage or relevance.


回答1:


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.



来源:https://stackoverflow.com/questions/49218730/can-i-make-different-variables-of-same-values-point-to-diffrent-objects

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!