Is there a logical difference between 'not ==' and '!= (without is)

我们两清 提交于 2019-11-29 14:10:25

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 ==

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

Different rich comparison methods are called depending on whether you use == or !=.

class EqTest(object):
    def __eq__(self, other):
        print "eq"
        return True
    def __ne__(self, other):
        print "ne"
        return False

a = EqTest()
b = EqTest()

print not (a == b)
# eq
# False
print a != b
# ne
# False

As far as I know, you will get the same result for all built-in types, but theoretically they could have different implementations for some user-defined objects.

I would use != instead of not and == simply because it is one operation instead of two.

Your first example is how you should be testing the result of find.

Your second example is doing too much. It is additionally performing a boolean not on the result of the each_line.find(":") == -1 expression.

In this context, where you want to use not is when you have something that you can test for truthiness or falsiness.
For example, the empty string '' evaluates to False:

s = ''
if not s:
    print('s is the empty string')

You seem to be conflating a little bit the identity-test expressions is and is not with the boolean not.

An example of how you'd perform an identity test:

result_of_comparison = each_line.find(":") == -1
if result_of_comparison is False: # alternatively: is not True
    pass
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!