0

When developing my program, I was faced with this problem, as different types of classes after inheritance.

For example:

class MyClass: pass

class MyClass2(MyClass): pass

A = MyClass()
B = MyClass2()
print(type(A) == type(B))

Result will be False, and that's not what I need. I tried to search some info in typing Python module, but I didn't really understand nature of types. What should I do for True result?

Patrick Artner
  • 50,409
  • 9
  • 43
  • 69
TTaykAH
  • 35
  • 5
  • 3
    That's why you don't compare types by equality; try `isinstance(B, MyClass)`. – jonrsharpe Apr 01 '20 at 21:26
  • 1
    Does this answer your question? [What's the canonical way to check for type in Python?](https://stackoverflow.com/questions/152580/whats-the-canonical-way-to-check-for-type-in-python) – Brian61354270 Apr 01 '20 at 21:26

1 Answers1

1

Every object has exactly one type, but that doesn't mean an object is an instance of exactly one type.

>>> type(A) == type(B)
False
>>> type(A)
<class '__main__.MyClass'>
>>> type(B)
<class '__main__.MyClass2'>

A and B have different types, but B is an instance of type(A)

>>> isinstance(B, MyClass)
True

because type(B) is a subclass of type(A).

>>> issubclass(type(B), type(A))
True
chepner
  • 497,756
  • 71
  • 530
  • 681