Pythonの不等号演算子

Pythonのノットイコール演算子は、2つの変数が同じ型で異なる値を持っている場合に`True`を返し、値が同じ場合は`False`を返します。Pythonは動的で強く型付けされた言語なので、2つの変数が同じ値を持っていても異なる型である場合、ノットイコール演算子は`True`を返します。

Pythonのノットイコール演算子

Operator Description
!= Not Equal operator, works in both Python 2 and Python 3.
<> Not equal operator in Python 2, deprecated in Python 3.

Python 2の例

Python 2.7でのノットイコール演算子の例を見てみましょう。

$ python2.7
Python 2.7.10 (default, Aug 17 2018, 19:45:58) 
[GCC 4.2.1 Compatible Apple LLVM 10.0.0 (clang-1000.0.42)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> 10 <> 20
True
>>> 10 <> 10
False
>>> 10 != 20
True
>>> 10 != 10
False
>>> '10' != 10
True
>>> 

Python 3の例

Python 3コンソールでの例です。

$ python3.7
Python 3.7.0 (v3.7.0:1bf9cc5093, Jun 26 2018, 23:26:24) 
[Clang 6.0 (clang-600.0.57)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> 10 <> 20
  File "<stdin>", line 1
    10 <> 20
        ^
SyntaxError: invalid syntax
>>> 10 != 20
True
>>> 10 != 10
False
>>> '10' != 10
True
>>> 

Python 3.6以降を使用している場合、f-stringsと一緒にPythonのノットイコール演算子を使用できます。

x = 10
y = 10
z = 20

print(f'x is not equal to y = {x!=y}')

flag = x != z
print(f'x is not equal to z = {flag}')

# python is strongly typed language
s = '10'
print(f'x is not equal to s = {x!=s}')

出力:

x is not equal to y = False
x is not equal to z = True
x is not equal to s = True

Python not equal with custom object

使用不等运算符时,它会调用__ne__(self, other)函数。因此,我们可以为对象定义自定义实现并更改自然输出。假设我们有一个Data类,其中包含字段 – id 和 record。当我们使用不等运算符时,我们只想比较记录值。我们可以通过实现我们自己的__ne__()函数来实现这一点。

class Data:
    id = 0
    record = ''

    def __init__(self, i, s):
        self.id = i
        self.record = s

    def __ne__(self, other):
        # return true if different types
        if type(other) != type(self):
            return True
        if self.record != other.record:
            return True
        else:
            return False


d1 = Data(1, 'Java')
d2 = Data(2, 'Java')
d3 = Data(3, 'Python')

print(d1 != d2)
print(d2 != d3)

输出:

False
True

请注意,d1和d2的记录值相同,但“id”不同。如果我们删除__ne__()函数,那么输出将如下所示:

True
True

您可以从我们的GitHub存储库中查看完整的Python脚本和更多Python示例。

Source:
https://www.digitalocean.com/community/tutorials/python-not-equal-operator