Reputation:
class a:
pass
class b(a):
pass
c = b()
type(c) == a #returns False
Is there an alternative to type()
that can check if an object inherits from a class?
Upvotes: 11
Views: 17231
Reputation: 63282
isinstance
and issubclass
are applicable if you know what to check against. If you don't know, and if you actually want to list the base types, there exist the special attributes __bases__
and __mro__
to list them:
To list the immediate base classes, consider class.__bases__
. For example:
>>> from pathlib import Path
>>> Path.__bases__
(<class 'pathlib.PurePath'>,)
To effectively recursively list all base classes, consider class.__mro__
or class.mro()
:
>>> from pathlib import Path
>>> Path.__mro__
(<class 'pathlib.Path'>, <class 'pathlib.PurePath'>, <class 'object'>)
>>> Path.mro()
[<class 'pathlib.Path'>, <class 'pathlib.PurePath'>, <class 'object'>]
If having an instance of a class, remember to first access its class using .__class__
.
Upvotes: 2
Reputation: 13121
>>> class a:
... pass
...
>>> class b(a):
... pass
...
>>> c = b()
>>> d = a()
>>> type(c) == type(d)
True
type()
returns a type object. a is the actual class, not the type
Upvotes: -1