user181351
user181351

Reputation:

Get base class type in Python

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

Answers (3)

Asclepius
Asclepius

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

Tyler Eaves
Tyler Eaves

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

albertov
albertov

Reputation: 2334

Yes, isinstance: isinstance(obj, Klass)

Upvotes: 26

Related Questions