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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With