python不等于运算符的具体使用 如果两个变量具有相同的类型并且具有不同的值 则Python不等于运算符将返回True 如果值相同则它将返回False 。Python is dynamic and strongly typed language, so if the two variables have the same values but they are of different type, then not equal operator will return True.Python是动态的强类型语言因此如果两个变量具有相同的值但它们的类型不同则不相等的运算符将返回True 。Python不等于运算符 (Python not equal operators)OperatorDescription!Not Equal operator, works in both Python 2 and Python 3.Not equal operator in Python 2, deprecated in Python 3.操作员描述不是Equal运算符可在Python 2和Python 3中使用。在Python 2中不等于运算符在Python 3中已弃用。Python 2示例 (Python 2 Example)Lets see some examples of not-equal operator in Python 2.7.我们来看一些Python 2.7中不等于运算符的示例。123456789101112131415$ python2.7Python2.7.10(default, Aug172018,19:45:58)[GCC4.2.1Compatible Apple LLVM10.0.0(clang-1000.0.42)] on darwinTypehelp,copyright,creditsorlicenseformore information.1020True1010False10!20True10!10False10!10TruePython 3示例 (Python 3 Example)Here is some examples with Python 3 console.这是Python 3控制台的一些示例。12345678910111213141516$ python3.7Python3.7.0(v3.7.0:1bf9cc5093, Jun262018,23:26:24)[Clang6.0(clang-600.0.57)] on darwinTypehelp,copyright,creditsorlicenseformore information.1020Filestdin, line11020^SyntaxError: invalid syntax10!20True10!10False10!10TrueWe can use Python not equal operator withf-strings too if you are using Python 3.6 or higher version.如果您使用的是Python 3.6或更高版本我们也可以将Python不等于运算符与f字符串一起使用。123456789101112x10y10z20print(fx is not equal to y {x!y})flagx !zprint(fx is not equal to z {flag})# python is strongly typed languages10print(fx is not equal to s {x!s})Output:输出x is not equal to y Falsex is not equal to z Truex is not equal to s TruePython不等于自定义对象 (Python not equal with custom object)When we use not equal operator, it calls __ne__(self, other) function. So we can define our custom implementation for an object and alter the natural output.当我们使用不等于运算符时它将调用__ne__(self, other)函数。 因此我们可以为对象定义自定义实现并更改自然输出。Lets say we have Data class with fields – id and record. When we are using the not-equal operator, we just want to compare it for record value. We can achieve this by implementing our own __ne__() function.假设我们有带字段的Data类-id和record。 当我们使用不等于运算符时我们只想比较它的记录值。 我们可以通过实现自己的__ne __函数来实现这一点。123456789101112131415161718192021222324classData:id0recorddef__init__(self, i, s):self.idiself.recordsdef__ne__(self, other):# return true if different typesiftype(other) !type(self):returnTrueifself.record !other.record:returnTrueelse:returnFalsed1Data(1,Java)d2Data(2,Java)d3Data(3,Python)print(d1 !d2)print(d2 !d3)Output:输出FalseTrueNotice that d1 and d2 record values are same but “id” is different. If we remove __ne__() function, then the output will be like this:请注意d1和d2记录值相同但“ id”不同。 如果删除__ne __函数则输出将如下所示TrueTrue