The difference of isinstance and type in Python
The type()
and isinstance()
are Python built-in functions that checks the type of an object.
class Food:
pass
i = isinstance(Food(), Food)
t = type(Food()) == Food
print(i) # True
print(t) # True
Inheritance
class Food:
pass
class Hamburger(Food):
pass
i = isinstance(Hamburger(), Food)
t = type(Hamburger()) == Food
print(i) # True
print(t) # False
Hamburger is a derived class. The hamburger is an instance of Food but the type of it not Food. The type of a hamburger is Hamburger.
The next example has a Cheeseburger class derived from Hamburger.
class Food:
pass
class Hamburger(Food):
pass
class Cheeseburger(Hamburger):
pass
i = isinstance(Cheeseburger(), Food)
t = type(Cheeseburger()) == Food
print(i) # True
print(t) # False
i = isinstance(Cheeseburger(), Hamburger)
t = type(Cheeseburger()) == Hamburger
print(i) # True
print(t) # False
The cheeseburger is an instance of Cheeseburger, Hamburger, and Food. But the type of it is Cheeseburger, not Hamburger.