判断 Python 中的某个类是否为第二个类的子类


若要在 Python 中判断某个类是否为第二个类的子类,请使用 numpy.issubclass_() 方法。第 1 个参数是输入类。如果 arg1 是 arg2 的子类,则返回 True。第 2 个参数是输入类。如果是类元组,则当 arg1 是其中任何元组元素的子类时返回 True。issubclass_ 等效于 Python 内置 issubclass,不同之处在于,如果任何参数不是类,它则返回 False,而不引发 TypeError。

步骤

首先,导入必要的库 -

import numpy as np

在 Numpy 中使用 issubclass_() 方法。检查某个类是否为第二个类的子类 -

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))

示例

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))

输出

Using the issubclass_() method in Numpy

Result... False
Result... True
Result... False
Result... False
Result... True
Result... False
Result... False
Result... False
Result... True

更新于: 2022 年 2 月 25 日

142 位浏览

开启您的 职业生涯

完成课程获得认证

开始
广告