Determine if a class is a subclass of a second class in Python

PythonNumpyServer Side ProgrammingProgramming

To determine if a class is a subclass of a second class, use the numpy.issubclass_() method in Python numpy. The 1st argument is the input class. True is returned if arg1 is a subclass of arg2. The 2nd argument is the input class. If a tuple of classes, True is returned if arg1 is a subclass of any of the tuple elements. The issubclass_ is equivalent to the Python built-in issubclass, except that it returns False instead of raising a TypeError if one of the arguments is not a class.

Steps

At first, import the required library −

import numpy as np

Using the issubclass_() method in Numpy. Checking whether a class is a subclass of a second class −

print("Result...",np.issubclass_(np.float16, np.float32))
print("Result...",np.issubclass_(np.int32, np.signedinteger))
print("Result...",np.issubclass_('i4', np.signedinteger))
print("Result...",np.issubclass_(np.int64, int))
print("Result...",np.issubclass_(np.float64, float))
print("Result...",np.issubclass_('S8', str))
print("Result...",np.issubclass_(np.int16, float))
print("Result...",np.issubclass_(np.array([45, 89]), int))
print("Result...",np.issubclass_(np.int32, np.integer))

Example

import numpy as np

# To determine if a class is a subclass of a second class, use the numpy.issubclass_() method in Python numpy
# The 1st argument is the input class. True is returned if arg1 is a subclass of arg2.
# The 2nd argument is the input class. If a tuple of classes, True is returned if arg1 is a subclass of any of the tuple elements.

# The issubclass_ is equivalent to the Python built-in issubclass,
# except that it returns False instead of raising a TypeError if one of the arguments is not a class.

print("Using the issubclass_() method in Numpy\n")

# Checking whether a class is a subclass of a second class
print("Result...",np.issubclass_(np.float16, np.float32))
print("Result...",np.issubclass_(np.int32, np.signedinteger))
print("Result...",np.issubclass_('i4', np.signedinteger))
print("Result...",np.issubclass_(np.int64, int))
print("Result...",np.issubclass_(np.float64, float))
print("Result...",np.issubclass_('S8', str))
print("Result...",np.issubclass_(np.int16, float))
print("Result...",np.issubclass_(np.array([45, 89]), int))
print("Result...",np.issubclass_(np.int32, np.integer))

Output

Using the issubclass_() method in Numpy

Result... False
Result... True
Result... False
Result... False
Result... True
Result... False
Result... False
Result... False
Result... True
raja
Updated on 25-Feb-2022 05:14:45

Advertisements