Python issubclass method


The issubclass() method is used to determine whether the argument class is a subclass of the type argument classinfo.

Related course: Complete Python Programming Course & Exercises

syntax

The following is the syntax of the issubclass() method:

issubclass(class, classinfo)

parameters

  • class -- class.
  • classinfo -- class.

return value

Returns True if class is a subclass of classinfo, False otherwise.

issubclass

The method issubclass() returns a boolean, either True or False depending on if the class is a subclass.

#! /usr/bin/python
# -*- coding: UTF-8 -*-

class A:
    pass

class B(A):
    pass

print(issubclass(B,A)) # return True

In the example above, the program returns True because class B inherits from class A.

class B(A):

If you try the opposite, it will return False because class A does not inherit from class B.

print(issubclass(A,B))

so only when a class inherits:

>>> issubclass(B,A)
True
>>> issubclass(A,B)
False
>>>

subclass()

By calling __subclass__() you get all the sub classes of a class. First define the classes of your program:

class A:
    pass

class B(A):
    pass

You can also retrieve the subclasses directly from a parent class like this:

>>> print("A", A.__subclasses__())
A [<class '__main__.B'>]

>>> print("B", B.__subclasses__())
B []
>>>

bases()

By calling __bases__() you get the base class. We use the same setup:

class A:
    pass

class B(A):
    pass

So class A is super class and class B inherits from class B.

>>> print("A", A.__bases__)
A (<class 'object'>,)

>>> print("B", B.__bases__)
B (<class '__main__.A'>,)