Im trying to compare types of two objects by using isinstance(obj1, type(obj2))
.
However, im not really sure how type infers the typing of an object - or whether theres a chance that the type returned is of an ancestor class.
Im trying to compare types of two objects by using isinstance(obj1, type(obj2))
.
However, im not really sure how type infers the typing of an object - or whether theres a chance that the type returned is of an ancestor class.
Given three classes A
, B
, C
. Class B
is subclass of A
and class C
is subclass of B
.
class A:
pass
class B(A):
pass
class C(B):
pass
Using type
on an object is the same thing as calling obj.__class__
. This returns the class to which an instance belongs.
isinstance
however also checks for subclasses. So your call isinstance(obj1, type(obj2))
depends on if the two objects are related.
>>> a = A()
>>> b = B()
>>> c = C()
>>> type(c) == type(b)
False
>>> isinstance(c, type(b))
True
Instance c
is of type <class '__main__.C'>
and b
is of type <class '__main__.B'>
. So the comparison using type
evaluates to False
.
A more elaborate example of your approach and using the class directly:
>>> isinstance(c, type(b)) # as C is subclass of B
True
>>> isinstance(c, B) # using the class directly
True
>>> isinstance(b, type(c)) # as b is of parent class B
False
>>> isinstance(b, C) # C is subclass of B, thus b is not an instance of C
False
>>> isinstance(c, type(a)) # C is subclass of B which is subclass of A
True