Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compare two classes/types in python?

Tags:

python

types

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

class ClassA(object):
    pass

class ClassB(object):
    pass

And in another module I am getting the attributes of the module:

import classes

Class1 = getattr(classes, 'ClassA')
Class2 = getattr(classes, 'ClassA')
print type(Class1) == type(Class2)

Class3 = getattr(classes, 'ClassA')
Class4 = getattr(classes, 'ClassB')
print type(Class3) == type(Class4)

Both type comparison are returning True and that's not what I was expecting.

How can I compare class types using python's native type values?

like image 954
E.Beach Avatar asked Apr 11 '14 12:04

E.Beach


Video Answer


1 Answers

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

>>> StupidClass is StupidClass

returns an expected True value.

So as we can see == operator on classes can be overloaded while there is no way (at least simple one) to change is operator's behavior.

like image 154
Azat Ibrakov Avatar answered Oct 03 '22 02:10

Azat Ibrakov