Andz
Andz

Reputation: 1325

Checking if A is superclass of B in Python

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 ?

Upvotes: 31

Views: 18421

Answers (4)

user235859
user235859

Reputation: 1174

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

>>> class p1(object): pass
>>> class p2(p1): pass
>>> p2.__bases__
(<class '__main__.p1'>,)

Upvotes: 46

Azeem.Butt
Azeem.Butt

Reputation: 5861

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

Upvotes: 6

Serge
Serge

Reputation: 7694

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

As follows:

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

issubclass(p2, p1)

Upvotes: 44

Joril
Joril

Reputation: 20547

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

Upvotes: 5

Related Questions