How I can check if A is superclass of B in Python?

In Python, you can check if class A is a superclass of class B using the built-in issubclass() function or by examining the __bases__ attribute. Let's explore both methods with practical examples.

Class Definition

First, let's define our example classes where A is the parent class and B inherits from A ?

class A(object):
    pass

class B(A):
    pass

Method 1: Using issubclass()

The issubclass() function returns True if the first argument is a subclass of the second argument ?

class A(object):
    pass

class B(A):
    pass

# Check if B is a subclass of A (meaning A is superclass of B)
result = issubclass(B, A)
print("Is B a subclass of A?", result)

# Check if A is a subclass of B (should be False)
result2 = issubclass(A, B)
print("Is A a subclass of B?", result2)
Is B a subclass of A? True
Is A a subclass of B? False

Method 2: Using __bases__ Attribute

The __bases__ attribute contains a tuple of the direct base classes (superclasses) of a class ?

class A(object):
    pass

class B(A):
    pass

# Check the base classes of B
print("Base classes of B:", B.__bases__)

# Check if A is in B's base classes
is_superclass = A in B.__bases__
print("Is A a direct superclass of B?", is_superclass)
Base classes of B: (<class '__main__.A'>,)
Is A a direct superclass of B? True

Multiple Inheritance Example

Here's how these methods work with multiple inheritance ?

class A(object):
    pass

class B(object):
    pass

class C(A, B):
    pass

# Check subclass relationships
print("Is C subclass of A?", issubclass(C, A))
print("Is C subclass of B?", issubclass(C, B))

# Check all base classes
print("Base classes of C:", C.__bases__)
Is C subclass of A? True
Is C subclass of B? True
Base classes of C: (<class '__main__.A'>, <class '__main__.B'>)

Comparison

Method Checks Best For
issubclass() All inheritance levels General inheritance checking
__bases__ Direct parent classes only Examining class hierarchy

Conclusion

Use issubclass(B, A) to check if A is a superclass of B at any inheritance level. Use __bases__ to examine only the direct parent classes of a class.

Updated on: 2026-03-24T19:41:25+05:30

397 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements