Python不等于运算符
时间:2020-02-23 14:43:04 来源:igfitidea点击:
如果两个变量具有相同的类型并且具有不同的值,则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 2016, 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 2016, 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或者更高版本,我们也可以将Python不等于运算符与f字符串一起使用。
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)函数。
因此,我们可以为对象定义自定义实现并更改自然输出。
假设我们具有带有字段(即id和record)的" Data"类。
当我们使用不等于运算符时,我们只想比较它的记录值。
我们可以通过实现自己的__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

