I thought in Python that:
All classes ultimately are subclasses of object
All classes utimately are instances of type
However after checking
isinstance(object,type)
which returned True
as expected. As object is an instance of type.
However I'm not sure why isinstance(type,object)
returns True
. (I thought this would be False
as type isn't an instance of object).
Particularly as isinstance(type,type)
is True
ie it's an instance of itself.
And also issubclass(object,type)
returns False
, which was expected, but the results above isinstance(type,object)
made me doubt wether I understood the relationships properly.
is it because isinstance works across subclasses but type doesn't?
is it because isinstance works across subclasses but type doesn't?
Exactly. type(x)
gives you the actual type of x, whereas isinstance(x, t)
checks whether the type of x
is t
or a subclass of t. Hence, isinstance(x, t)
is True
even when type(x) == t
would not.
In particular, object
is the base class from which all other classes inherit, thus type
, i.e. type(type)
, is also a subclass of object
and isinstance(type, object)
is true.
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