Python __subclasses__ and how to get child class name from parent class

When a class has a parent class in Python, we can get the child class name from the parent class.

class Product:

    def __init__(self, price):
        self.price = price


class Book(Product):

    def __init__(self, price, page):
        super().__init__(price)
        self.page = page


s = Product.__subclasses__()

print(s)  # [<class '__main__.Book'>]
print(type(s))  # <class 'list'>

t = s[0]

print(t)  # <class '__main__.Book'>

n = t.__name__

print(n)  # Book
  • parent ... Product
  • child ... Book

Product, not Product instance, has the __subclasses__ method that returns a list of child classes. So t has Book class information and t.__name__ is Book, Product's child class name.

If the class doesn't have any child class, __subclasses__ returns an empty list.

class Product:

    def __init__(self, price):
        self.price = price


s = Product.__subclasses__()

print(s)  # []

Python Class

Python Tutorial