📜  Python NOT EQUAL运算符

📅  最后修改于: 2022-05-13 01:55:06.269000             🧑  作者: Mango

Python NOT EQUAL运算符

在本文中,我们将看到 != (Not equal)运算符。在Python!=被定义为不等于运算符。如果两边的操作数不相等返回true,并返回false,如果他们是平等的。

注意:要记住,这个比较运算符将返回True如果值是相同的,但有不同的数据类型是很重要的。

示例 1:比较相同数据类型的不同值

Python3
A = 1
B = 2
C = 2
 
print(A!=B)
print(B!=C)


Python3
A = 1
B = 1.0
C = "1"
 
print(A!=B)
print(B!=C)
print(A!=C)


Python3
class Student:
 
    def __init__(self, name):
        self.student_name = name
 
    def __ne__(self, x):
        # return true for different types
        # of object
        if type(x) != type(self):
            return True
           
        # return True for different values
        if self.student_name != x.student_name:
            return True
        else:
            return False
 
s1 = Student("Shyam")
s2 = Student("Raju")
s3 = Student("babu rao")
 
print(s1 != s2)
print(s2 != s3)


输出:

True
False

示例 2:比较不同数据类型的相同值

蟒蛇3

A = 1
B = 1.0
C = "1"
 
print(A!=B)
print(B!=C)
print(A!=C)

输出:



False
True
True

示例 3: Python不等于自定义对象

每当使用不等于运算符时,就会调用__ne__() 。我们可以覆盖这个函数来改变不等于运算符的性质。

蟒蛇3

class Student:
 
    def __init__(self, name):
        self.student_name = name
 
    def __ne__(self, x):
        # return true for different types
        # of object
        if type(x) != type(self):
            return True
           
        # return True for different values
        if self.student_name != x.student_name:
            return True
        else:
            return False
 
s1 = Student("Shyam")
s2 = Student("Raju")
s3 = Student("babu rao")
 
print(s1 != s2)
print(s2 != s3)

输出:

True
True