Skip to main content
 首页 » 编程设计

python之isinstance(...) 的功能;但没有实例

2025年05月04日17mfryf

<分区>

在运行时,我想检查指定的子类是否派生自指定的父类。

有了对象实例,就很简单了:

def is_related(child_instance, parent_type): 
    return isinstance(child_instance, parent_type) 

有没有办法在不拥有(或创建)子实例的情况下执行此操作,而是引用子类型?

有点像...

def is_related(child_type, parent_type): 
    return is_child_class(child_type, parent_type) 

为 is_child_class 提供一个实现将回答这个问题。

(相比之下,C# 中的类型知道它们的父类(super class)型。我不知道这在 Python 中是否也是如此。)