Python 类继承判断:如何在父类中判断子类是否继承接口
在 Python 类继承中,有时需要在父类中判断子类是否继承了一个接口。可以使用 isinstance() 函数来实现这个功能。isinstance() 函数接受两个参数,第一个参数为要判断的对象,第二个参数为要判断的类型。如果对象是指定类型或者是该类型的子类,则返回 True;否则返回 False。
以下是一个示例代码:
class ClassC:
def check_interface(self, obj):
if isinstance(obj, SomeInterface):
print('ClassA继承了SomeInterface')
else:
print('ClassA没有继承SomeInterface')
class ClassB(ClassC):
pass
class ClassA(ClassB, SomeInterface):
pass
class SomeInterface:
pass
obj = ClassA()
b = ClassB()
b.check_interface(obj)
输出结果为:
ClassA继承了SomeInterface
在示例代码中,ClassA 继承了 ClassB 和 SomeInterface,ClassB 继承了 ClassC,因此可以在 ClassC 的 check_interface() 方法中使用 isinstance() 函数来判断 ClassA 是否继承了 SomeInterface 接口。
原文地址: https://www.cveoy.top/t/topic/qxOY 著作权归作者所有。请勿转载和采集!