Python 不等于运算符

Python 不等式运算符返回True,如果两个变量具有相同类型和不同的值,如果值相同,则返回False

Python不等同操作员

操作员

Python 2 例子

让我们来看看 Python 2.7 中的一些非等式运算符的例子。

 1$ python2.7
 2Python 2.7.10 (default, Aug 17 2018, 19:45:58) 
 3[GCC 4.2.1 Compatible Apple LLVM 10.0.0 (clang-1000.0.42)] on darwin
 4Type "help", "copyright", "credits" or "license" for more information.
 5>>> 10 <> 20
 6True
 7>>> 10 <> 10
 8False
 9>>> 10 != 20
10True
11>>> 10 != 10
12False
13>>> '10' != 10
14True
15>>>

Python 2 Not Equal Operators

Python 3 例子

以下是使用Python 3控制台的一些例子。

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

Python Not Equal Operator We can use Python not equal operator with f-strings too if you are using Python 3.6 or higher version.

 1x = 10
 2y = 10
 3z = 20
 4
 5print(f'x is not equal to y = {x!=y}')
 6
 7flag = x != z
 8print(f'x is not equal to z = {flag}')
 9
10# python is strongly typed language
11s = '10'
12print(f'x is not equal to s = {x!=s}')

输出:

1x is not equal to y = False
2x is not equal to z = True
3x is not equal to s = True

Python 不等于定制对象

当我们使用不平等的操作员时,它会称之为(自我,其他)函数,所以我们可以定义对象的自定义实现,并改变自然的输出。 假设我们有数据类的字段 - id 和记录。 当我们使用不平等的操作员时,我们只想将其与记录值进行比较。 我们可以通过实施我们自己的()函数来实现这一点。

 1class Data:
 2    id = 0
 3    record = ''
 4
 5    def __init__(self, i, s):
 6        self.id = i
 7        self.record = s
 8
 9    def __ne__(self, other):
10        # return true if different types
11        if type(other) != type(self):
12            return True
13        if self.record != other.record:
14            return True
15        else:
16            return False
17
18d1 = Data(1, 'Java')
19d2 = Data(2, 'Java')
20d3 = Data(3, 'Python')
21
22print(d1 != d2)
23print(d2 != d3)

输出:

1False
2True

请注意,d1和d2的记录值是相同的,但id是不同的。如果我们删除()函数,那么输出将是这样的:

1True
2True

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

Published At
Categories with 技术
Tagged with
comments powered by Disqus