如何测试一个对象是否是另一个对象? [英] How to test if an object IS another object?
问题描述
如果两个对象具有相同的值,则可以将它们与==进行比较。我想要做的就是找出两个对象实际上只是对同一个对象的引用,我怎么能用Python做到这一点?
谢谢
If two objects are of equal value you can compare them with ==. What I
want to do is find out if two objects are actually just references to
the same object, how can I do this in Python?
Thanks
推荐答案
da ******* @ gmail.com écrit:
如果两个对象具有相同的值,您可以将它们与==进行比较。我想要做的是找出两个对象实际上是否只是对同一个对象的引用,我该如何在Python中执行此操作?
If two objects are of equal value you can compare them with ==. What I
want to do is find out if two objects are actually just references to
the same object, how can I do this in Python?
最明显的方式(像往常一样?):
如果obj1是obj2:
//你的代码在这里
The most obvious way (as usual ?):
if obj1 is obj2:
// your code here
对于删除我的消息感到抱歉,我发布了错误的谷歌
帐户,我真的不希望我的电子邮件在那些恼人的垃圾邮件机器人
可以找到它。
Sorry about removing my message, I posted with the wrong google
account, I don''t really want my email where those irritating spam bots
can find it.
最明显的方式(像往常一样?):
如果obj1是obj2:
//你的代码在这里
我马上就想到了,并在控制台上对它进行了测试,但它没有像我预期的那样工作:
foo = 3
bar = 3
zoo = foo
foo是动物园
Truefoo是酒吧
Truezoo是酒吧
The most obvious way (as usual ?):
if obj1 is obj2:
// your code here
I immediately thought of is, and tested it in the console, but it
didn''t work quite like I expected:
foo = 3
bar = 3
zoo = foo
foo is zoo Truefoo is bar Truezoo is bar
True
很明显foo和bar有相同的价值,但它们是不同的对象
不是吗?然而应用is运算符产生True。
谢谢,
-Dan
True
clearly foo and bar have the same value but they are different objects
aren''t they? Yet applying the is operator yields True.
Thanks,
-Dan
el******@yahoo.com 写道:
foo = 3
bar = 3
foo = 3
bar = 3
很明显foo和bar有相同的值,但它们是不同的对象
不是吗?
clearly foo and bar have the same value but they are different objects
aren''t they?
不,他们是同一个对象。现在尝试使用300而不是3 ;-)。
No, they''re the same object. Now try it with 300 instead of 3 ;-).
这篇关于如何测试一个对象是否是另一个对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!