# - Darling, I want some pudding!
# - There is some in the fridge.
pudding_to_eat = fridge_pudding
pudding_to_eat is fridge_pudding
# => True
# - Honey, what's with all the dirty dishes?
# - I wanted to eat pudding so I made some. Sorry about the mess, Darling.
# - But there was already some in the fridge.
pudding_to_eat = make_pudding(ingredients)
pudding_to_eat is fridge_pudding
# => False
is
:测试两个变量是否指向同一对象,而不是两个变量是否具有相同的值。你知道吗Nicely put:
is
运算符检查两个操作数是否引用同一对象。在这种情况下,l1和l2是两个不同的对象,因此,它返回False。你知道吗请注意,两个列表实例引用同一对象并不是因为它们具有相同的内容。你知道吗
您可以使用
id
检查两者是否引用同一对象。检查以下代码。在本例中,您可以看到l1
和l2
是不同的对象,而l2
和l3
是指同一个对象。请注意,在下面的代码中使用==
运算符,以及如果列表的内容相同,它如何返回True
。你知道吗输出:
注意:如果要根据内容比较两个对象,请使用
==
操作符因此,
==
运算符比较两个对象或变量的值,is
运算符检查比较的对象是否相同。你可以把它想象成比较pointers
。你知道吗相关问题 更多 >
编程相关推荐