'not ==' 和 '!= (没有 is) 之间是否存在逻辑差异 [英] Is there a logical difference between 'not ==' and '!= (without is)

查看:41
本文介绍了'not ==' 和 '!= (没有 is) 之间是否存在逻辑差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Python 3.x 之间是否存在实质性差异:

Is there a substantial difference in Python 3.x between:

for each_line in data_file:
    if each_line.find(":") != -1:
        #placeholder for code
        #more placeholder

for each_line in data:
    if not each_line.find(":") == -1:
        #placeholder for code
        #more placeholder

我的问题不是针对上述用法,而是更普遍或更重要的问题 - 即使结果相同,这种语法差异是否以不同的方式起作用?逻辑上有区别吗?是否有更合适的任务,或者这仅仅是风格上的差异?如果这仅仅是风格,Python 程序员认为哪个更简洁?

My question isn't particular to the above usage, but is more general or essential - is this syntactical difference working in a different way, even though the result is the same? Is there a logical difference? Are there tasks where one is more appropriate or is this solely a stylistic difference? If this is merely stylistic, which one is considered cleaner by Python programmers?

另外,上面是问is==有什么区别的反例吗?前者和后者一样,是对象身份和对象值相等的区别吗?我的意思是,在我上面的例子中,使用 not 时的 is 是隐式的吗?

Also, is the above an opposite instance of asking what the difference is between is and ==? Is the former, like the latter, a difference of object identity and object value equality? What I mean is, in my above example, is the is in using not implicit?

推荐答案

据我所知,在功能上它们并不完全相同;如果您正在与类进行比较,则该类可能有一个成员函数,__ne__ 在使用比较运算符 != 时调用,而不是 __eq__ 时调用使用比较==

As I understand it, functionally they are not entirely the same; if you are comparing against a class, the class could have a member function, __ne__ which is called when using the comparison operator !=, as opposed to __eq__ which is called when using the comparison ==

所以,在这种情况下,
not (a == b) 会在 a 上调​​用 __eq__,以 b 作为参数,然后 not 结果
(a != b) 会在 a 上调​​用 __ne__,以 b 作为参数.

So, in this instance,
not (a == b) would call __eq__ on a, with b as the argument, then not the result
(a != b) would call __ne__ on a, with b as the argument.

我会使用第一种方法(使用 !=)进行比较

I would use the first method (using !=) for comparison

这篇关于'not ==' 和 '!= (没有 is) 之间是否存在逻辑差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆