Python issubclass()

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.

如果classclassinfo的子类,则此函数返回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()函数非常相似,除了前者适用于类,而后者适用于类的实例。

GitHub Repository. GitHub存储库中检出完整的python脚本和更多Python示例。

Reference: Official Documentation

参考: 官方文档

翻译自: https://www.journaldev.com/22938/python-issubclass

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值