在Python中,当您要测试对象foo
是Foo
的实例时,您可以这样做:
if isinstance(foo, Foo):
# do something
现在,假设Foo
类是继承自Bar
的专门类,并且还有很多其他类继承自我:Foo1
,{{1 }},Foo2
,...
,它们继承自FooX
类。
Bar
可以是任何foo
类中的一个实例。我感兴趣的是知道Foox
来自一类从foo
继承的类。您知道简单/规范的方法吗?
答案 0 :(得分:1)
正确的方法可能是测试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