在 Python 中,当你想测试一个对象时 foo是 Foo 的实例你这样做:
if isinstance(foo, Foo):
# do something
现在,想象一下 Foo class 是继承自 Bar 的特殊类并且还有很多其他类继承自它:我有 Foo1 , Foo2 , ... , FooX , 继承自 Bar类。
foo可能是这些 Foox 中的任何一个的实例类(class)。我感兴趣的是知道 foo来自有一天从 Bar 继承的类.您知道一种简单/规范的方法吗?
请您参考如下方法:
正确的做法应该是测试foo是否是一个Bar对象,这说明Foo继承自Bar.
class Bar:
pass
class Foo(Bar):
pass
foo = Foo()
isinstance(foo, Bar)
输出:
True
您还可以检查类 Foo 是否是类 Bar 的子类:
issubclass(Foo, Bar) # notice Foo, the class, not the instance foo
