在Python中创建两个具有相同值的不可变对象 [英] Create two immutable objects with the same value in Python
问题描述
在Python中是否可以创建两个具有相同值的不可变对象?
Is it possible in Python to create two immutable objects with the same value?
为使您理解我的意思,下面是一些示例:
So that you understand what I mean, here are some examples:
>>> a = 13
>>> b = 13
>>> a is b
True
>>> a = 13
>>> b = 26/2
>>> a is b
True
>>> a = 13
>>> b = int.__new__(int, 13)
>>> a is b
True
>>> a = 13
>>> b = int("13")
>>> a is b
True
是否可以用相同的值创建a
和b
,但a is b
返回False
?
只是学习....:D
Is it possible to create a
and b
with the same value but a is b
to return False
?
Just learning.... :D
推荐答案
当然,只需选择一个太大而无法缓存的值即可.
Sure, just choose a value that is too large to be cached:
>>> a = 256
>>> b = 256
>>> a is b
True
>>> a = 257
>>> b = 257
>>> a is b
False
>>> a = "hey"
>>> b = "hey"
>>> a is b
True
>>> a = "hey!"
>>> b = "hey!"
>>> a is b
False
将仅缓存小整数和短字符串(这是与实现有关的,因此无论如何您都不应依赖它). is
只能用于测试对象 identity ,而不能用于测试 quality .
Only small integers and short strings will be cached (and this is implementation-dependent, so you shouldn't rely on that anyway). is
should only be used for testing object identity, never for testing equality.
这篇关于在Python中创建两个具有相同值的不可变对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!