Python issubclass() function is used to check if a class is a subclass of another class or not.
Python的issubclass()函数用于检查一个类是否为另一个类的子类。
Python issubclass() (Python issubclass())
Python issubclass() function syntax is:
Python的issubclass()函数语法为:
issubclass(class, classinfo)
This function returns True
if class is a subclass of classinfo.
如果class是classinfo的子类,则此函数返回True
。
A class is considered a subclass of itself. We can also pass a tuple of classes as the classinfo argument, in that case, the function will return True if class is a subclass of any of the classes in the tuple.
类被认为是其自身的子类。 我们还可以传递一个类的元组作为classinfo参数,在这种情况下,如果class是该元组中任何类的子类,则函数将返回True。
Since the object
is the base class in Python, the function will return True if classinfo is passed as object
class.
由于object
是Python中的基类,因此如果将classinfo作为object
类传递,则函数将返回True。
Python issubclass()示例 (Python issubclass() example)
Let’s define some classes and subclasses for our example.
让我们为示例定义一些类和子类。
class Super:
pass
class Child(Super):
pass
class GrandChild(Child):
pass
Now let’s see the output of issubclass() function with different arguments.
现在,让我们看看带有不同参数的issubclass()函数的输出。
print(issubclass(Child, Super)) # 1st level inheritance
print(issubclass(GrandChild, Super)) # multilevel inheritance
print(issubclass(Child, Child)) # same class
print(issubclass(Super, tuple)) # no inheritance
print(issubclass(Super, object)) # object is the base class
Output:
输出:
True
True
True
False
True
具有类元组的Python issubclass() (Python issubclass() with tuple of classes)
print(issubclass(GrandChild, (str, list, Super)))
Output: True
输出: True
Let’s have a look at another example where we will check if OrderedDict is a subclass of dict or not.
让我们看另一个示例,在该示例中,我们将检查OrderedDict是否为dict的子类。
from collections import OrderedDict
print(issubclass(OrderedDict, dict))
Output: True
输出: True
Python issubclass()与isinstance() (Python issubclass() vs isinstance())
Python issubclass() and isinstance() functions are very similar, except that former works with classes whereas later works with instance of classes.
Python的issubclass()和isinstance()函数非常相似,除了前者适用于类,而后者适用于类的实例。
Reference: Official Documentation
参考: 官方文档