30
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 ?

joozek
  • 2,143
  • 2
  • 21
  • 32
Andz
  • 1,315
  • 1
  • 12
  • 14

4 Answers4

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'>,)
user235859
  • 1,174
  • 1
  • 10
  • 6
  • 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 02 '12 at 17:51
  • 3
    For my question, issubclass() was the better answer, but this answer is also appreciated. – Andz Jun 02 '12 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 '13 at 23:05
43

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

As follows:

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

issubclass(p2, p1)
Serge
  • 7,706
  • 5
  • 40
  • 46
  • 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 09 '13 at 11:51
  • 1
    @limiacs, for me who thinks classes as `set`, this doesn't bother me. A is a subset of A. – Vineet Menon Mar 13 '15 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. –  Sep 04 '18 at 08:44
  • 1
    how to evaluate to true only if subclass but not itself? see first comment – droid192 Jan 09 '19 at 19:26
  • @qrtLs, if A should be a true subclass of B you can do this: `issubclass(A,B) and not A == B` – stefan croes Oct 04 '22 at 08:09
6

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

Azeem.Butt
  • 5,855
  • 1
  • 26
  • 22
5

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

Joril
  • 19,961
  • 13
  • 71
  • 88