Yunti
Yunti

Reputation: 7498

instance(object, type) returns True, should it not be False?

I thought in Python that:

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?

Upvotes: 4

Views: 76

Answers (1)

tobias_k
tobias_k

Reputation: 82949

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.

Upvotes: 4

Related Questions