Python不等于运算符
时间:2020-02-23 14:43:04 来源:igfitidea点击:
在本教程中,我们将看到Python不等于运算符。
不是相同的运算符表示表示 !=在Python中,当两个变量相同但具有不同的值时,返回true。
如果两个变量可能相同,则不等于运算符将返回 False。
Python不等于运算符示例
这是不相等运算符的简单示例
print(2.2!=2)
这将打印真实。
str1 = "world" str2 = "world" str3 = "WORLD" print(str1!=str2) print(str1!=str3)
输出:
错误的真实
str1!= str2返回false:astr1和str2与字符串完全相同,因此返回false。
str1!= str3返回true:在str1和str3不同时,它返回true。
Please note that you can use <> for not equal in Python 2 but <> is deprecated in Python 3.
在自定义对象时,Python不等于运算符
当你调用的时候!=,Python内部调用 __ne__(self, other)方法。
在自定义对象的情况下,我们可以在类中实现自己的版本。
这是快速的例子。
class Country:
name = ''
population = 0
def __init__(self, name, population):
self.name = name
self.population = population
def __ne__(self, other):
# If different type, you can return true
if type(other) != type(self):
return True
if self.name != other.name:
return True
else:
return False
Netherlands1 = Country('Netherlands', 1000)
Netherlands2 = Country('Netherlands', 2000)
china = Country('China', 3000)
print(Netherlands1 != Netherlands2)
print(Netherlands1 != china)
输出:
False True

