我需要比较两个对象实例的相等性,并且通常在我想这样做的时候使用is
;但是在调试了几个小时的一些失败代码之后,有时我发现了这个问题。只是我调试的一段代码。你知道吗
print "EVENT OBJECT:", id(event.source), "AND BINDING COMPONENT:", id(self.component), "IS THE SAME:", event.source is self.component
输出:
EVENT OBJECT: 4 AND BINDING COMPONENT: 4 IS THE SAME: False
但是,像这样使用==
:
print "EVENT OBJECT:", id(event.source), "AND BINDING COMPONENT:", id(self.component), "IS THE SAME:", event.source == self.component
输出:
EVENT OBJECT: 4 AND BINDING COMPONENT: 4 IS THE SAME: True
我追求的结果是第二个输出。你知道吗
有人能解释吗?我以为我用is
做对了。我对Python很陌生,几个月前才从.Net和C#开始这个项目。你知道吗
编辑:
不是this的复制品,因为我知道is
和==
之间的区别。事实上,我读过其他帖子,他们似乎没有回答我的问题,为什么帖子中的代码会有这样的行为。你知道吗
更新:
下面是init方法的一个片段,我在其中存储组件。你知道吗
def __init__(self, component, *bindings):
self.__dict__['component'] = component
print "COMPONENT ID:", hex(id(component)), "COMPONENT IN SELF ID", hex(id(self.component))
self.__dict__['_bindings'] = bindings
这将输出:
COMPONENT ID: 0x18 COMPONENT IN SELF ID 0x18
然后在事件处理程序中:
print "EVENT OBJECT:", hex(id(event.source)), "AND BINDING COMPONENT:", hex(id(self.component)), "IS THE SAME:", event.source is self.component
我得到这个输出:
EVENT OBJECT: 0x18 AND BINDING COMPONENT: 0x18 IS THE SAME: False
只有当两个对象指向同一个变量时,
is
操作符才返回True。考虑以下情况:相关问题 更多 >
编程相关推荐