Python Equality Check Difference

后端 未结 4 851
甜味超标
甜味超标 2021-02-05 00:37

Suppose we want some block of code to be executed when both \'a\' and \'b\' are equal to say 5. Then we can write like :

if a == 5 and b == 5:
    # do something         


        
4条回答
  •  情深已故
    2021-02-05 01:03

    It depends. You could write your own custom __eq__ which allows you to compare yourself to ints and things:

     class NonNegativeInt(object):
       def __init__(self, value):
         if value < 0:
           raise Exception("Hey, what the...")
         self.value = value
    
       def __eq__(self, that):
         if isinstance(that, int):
           return self.value == that
         elif isinstance(that, NonNegativeInt):
           return self.value == that.value
         else:
           raise ArgumentError("Not an acceptible argument", "__eq__", that)
    

    which would work different depending on comparing "b" to "a" and "b" to an "int." Hence, a == b could be false while a == 5 and b == 5 could be True.

提交回复
热议问题