Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python issubclass() Function

Python issubclass() Function

Python3 Built-in Functions Python3 built-in function


issubclass() is a built-in Python function that checks whether a class is a subclass of another class.

issubclass() It determines the inheritance relationship between classes and can check both direct and indirect subclasses.

Word meaning: issubclass 是 is a subclass(是一个子类)的缩写。


Basic syntax and parameters

Syntax format

issubclass(class, classinfo)

Parameter Description

Function description


Example

Example 1: basic usage

Example

# Class definition
class Animal:
    pass

class Dog(Animal):
    pass

class Cat(Animal):
    pass

class Husky(Dog):
    pass

# Check the inheritance relationship
print(issubclass(Dog, Animal))    # Output: True
print(issubclass(Cat, Animal))    # Output: True
print(issubclass(Dog, Cat))       # Output: False

# Indirect inheritance
print(issubclass(Husky, Animal))   # Output: True (inheritance chain: Husky -> Dog -> Animal)
print(issubclass(Husky, Dog))      # Output: True

Expected output:

True
True
False
True
True

Code analysis:

  1. A subclass is a subclass of its parent class.
  2. Indirect inheritance (a grandchild class) is also a subclass of the ancestor class.

Example 2: using a tuple of classes

Example

# Check whether it belongs to one of several classes
class Animal:
    pass

class Dog(Animal):
    pass

class Cat(Animal):
    pass

class Robot:
    pass

print(issubclass(Dog, (Animal, Robot)))  # Output: True
print(issubclass(Dog, (Cat, Robot)))      # Output: False

# A class is also a subclass of itself
print(issubclass(int, int))    # Output: True
print(issubclass(str, str))    # Output: True

# Abstract base class
from collections.abc import MutableSequence
print(issubclass(list, MutableSequence))  # Output: True

Actual output:

The output depends on the actual run.

Code analysis:

Example 3: practical applications

Example

# Polymorphism implementation
class Shape:
    def area(self):
        raise NotImplementedError

class Circle(Shape):
    def __init__(self, radius):
        self.radius = radius

    def area(self):
        return 3.14 * self.radius ** 2

class Rectangle(Shape):
    def __init__(self, width, height):
        self.width = width
        self.height = height

    def area(self):
        return self.width * self.height

# Check the type
shapes = [Circle(5), Rectangle(3, 4), Circle(2)]
for shape in shapes:
    if issubclass(type(shape), Shape):
        print(f"Area: {shape.area()}")

# Use isinstance (recommended)
for shape in shapes:
    if isinstance(shape, Shape):
        print(f"Shape area: {shape.area()}")

Result:

Running in a real environment outputs the area of each shape.

Note: in real programming, it is common to use isinstance() instead of issubclass(type())。


Python3 Built-in Functions Python3 built-in function