31
class p1(object): pass
class p2(p1): pass

So p2 is the subclass of p1. Is there a way to find out programmatically that p1 is [one of] the superclass[es] of p2 ?

4 Answers 4

46

using <class>.__bases__ seems to be what you're looking for...

>>> class p1(object): pass
>>> class p2(p1): pass
>>> p2.__bases__
(<class '__main__.p1'>,)
3
  • 14
    @nikow, right... but the issue with issubclass() is that it requires giving a class to compare against, whereas __ bases __ will just give you the superclass(es) outright. Both solutions can be useful depending on the circumstances.
    – Andz
    Jun 2, 2012 at 17:51
  • 3
    For my question, issubclass() was the better answer, but this answer is also appreciated.
    – Andz
    Jun 2, 2012 at 17:57
  • 1
    __bases__ will only give you the direct parents (the ones in the parenthesis of the class definition), while issubclass checks the entire chain of inheritance.
    – wuerg
    Apr 14, 2013 at 23:05
44

Yes, there is way. You can use a issubclass function.

As follows:

class p1(object):pass
class p2(p1):pass

issubclass(p2, p1)
5
  • 2
    Attention: issubclass(A, A) evaluates to True. This may not be intuitive. At least to me, it seems obvious that a class is not its own subclass. issubclass should have been called istypeofclass.
    – ilmiacs
    Jan 9, 2013 at 11:51
  • 1
    @limiacs, for me who thinks classes as set, this doesn't bother me. A is a subset of A. Mar 13, 2015 at 11:06
  • @VineetMenon true, that is most likely the reason, but programming languages are not only meant for mathematicians, and it is definitely not intuitive for most people to think that a class is a subclass of itself.
    – user4396006
    Sep 4, 2018 at 8:44
  • 1
    how to evaluate to true only if subclass but not itself? see first comment
    – droid192
    Jan 9, 2019 at 19:26
  • @qrtLs, if A should be a true subclass of B you can do this: issubclass(A,B) and not A == B Oct 4, 2022 at 8:09
6

Depending on what you're trying to do, the "mro" method can also be useful.

5

I think you meant to use "class" instead of "def".. :) Anyway, try p2.__bases__

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.