Python不等运算符示例| Python中不等于运算符

Python Not Equal Operator Example是今天的主题。 Python是动态且强类型的语言,因此如果两个变量具有相同的值,但它们具有不同的类型,则不等于运算符将返回True。对于比较对象标识,您可以使用关键字is,而其否定则不是。

Python不等于运算符

如果两个变量的类型相同且值不同,则Not equal运算符返回True,如果值相同,则返回False。

print(1 == 1) print(1 != 1) print(() is ())

查看输出。

➜  pyt python3 app.py True False False ➜  pyt

请参见下表。

操作者 描述
= Not Equal运算符适用于Python 2和Python 3。
<> Python 2中不等于运算符,在Python 3中已弃用。

当两个值不同时,有=(不等于)运算符返回True,但要注意类型,因为“1= 1”。这将始终返回True,“1”== 1将始终返回False,因为类型不同。 Python是动态的,但强类型,其他静态类型的语言会抱怨比较不同的类型。

如果您使用的是Python 3.6或更高版本,我们也可以使用Python不等于f字符串的运算符。

# app.py  x = 11 y = 21 z = 19  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 = '11' print(f'x is not equal to s = {x!=s}')

查看输出。

➜  pyt python3 app.py x is not equal to y = True x is not equal to z = True x is not equal to s = True ➜  pyt

Python与自定义对象不相同

当我们使用不等于运算符时,它调用__ne __(self,other)函数。因此,我们可以定义对象的自定义实现并更改自然输出。

假设我们有带有字段的数据类 – id和record。当我们使用不等于运算符时,我们希望将其与记录值进行比较。我们可以通过实现__ne __()函数来实现这一点。

请参阅以下代码。

# app.py  class App:     id = 0     netflix = ''      def __init__(self, i, s):         self.id = i         self.netflix = s      def __ne__(self, other):         # return true if different types         if type(other) != type(self):             return True         if self.netflix != other.netflix:             return True         else:             return False   d1 = App(1, 'Stranger Things') d2 = App(2, 'Money Heist') d3 = App(3, 'Sacred Games')  print(d1 != d2) print(d2 != d3)

查看输出。

➜  pyt python3 app.py True True ➜  pyt

最后,Python Not Equal Operator Example结束了。

推荐帖子

Python示例中的空对象

Python property()示例

Python pow()示例

Python open()示例

Python iter()示例

资讯来源:由0x资讯编译自APPDIVIDEND,版权归作者Krunal所有,未经许可,不得转载
你可能还喜欢