Comparing two class types in python

前端 未结 4 2106
时光取名叫无心
时光取名叫无心 2021-02-20 12:07

I have two classes defined in a module classes.py:

class ClassA(object):
    pass

class ClassB(object):
    pass

And in another m

4条回答
  •  时光说笑
    2021-02-20 12:38

    If you want to check if types are equal then you should use is operator.

    Example: we can create next stupid metaclass

    class StupidMetaClass(type):
        def __eq__(self, other):
            return False
    

    and then class based on it:

    • in Python 2

      class StupidClass(object):
          __metaclass__ = StupidMetaClass
      
    • in Python 3

      class StupidClass(metaclass=StupidMetaClass):
          pass
      

    then a simple check

    StupidClass == StupidClass
    

    returns False, while the next check returns an expected True value

    StupidClass is StupidClass
    

    So as we can see == operator can be overridden while there is no simple way to change is operator's behavior.

提交回复
热议问题