“Python不等于运算符” can be paraphrased as “Python的不等于操作符”.

Python的不等运算符在两个变量类型相同但值不同的情况下返回True,如果值相同,则返回False。Python是一种动态且强类型的语言,因此,如果两个变量具有相同的值但是类型不同,不等运算符将返回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 2 Not Equal Operators

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 Not Equal Operator
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与自定义对象不相等。

当我们使用不等于操作符时,它会调用__ne__(self, other)函数。因此,我们可以为对象定义自己的实现并改变默认的输出结果。假设我们有一个名为Data的类,其中包含id和record这两个字段。当使用不等于操作符时,我们只想比较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
广告
将在 10 秒后关闭
bannerAds