在运行时,我想检查指定的子类是否派生自指定的父类。
使用对象实例,很容易:
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#中的类型知道它们的超类型。我不知道在Python中是否也是如此。)
假设这ChildClass
是的子类ParentClass
。然后
issubclass(ChildClass, ParentClass)
会回来 True
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句