开发者

What is the issubclass equivalent of isinstance in python?

开发者 https://www.devze.com 2022-12-10 06:24 出处:网络
Given an object, how do I tell if it\'s a class, and a subclass of a given class Foo? e.g. class Bar(Foo):

Given an object, how do I tell if it's a class, and a subclass of a given class Foo?

e.g.

class Bar(Foo):
  pass

isinstance(Bar(), Foo) # => True

issubclass(Bar, Foo) # <--- how do I do开发者_运维技巧 that?


It works exactly as one would expect it to work...

class Foo():
    pass

class Bar(Foo):
    pass

class Bar2():
    pass

print issubclass(Bar, Foo)  # True
print issubclass(Bar2, Foo) # False

If you want to know if an instance of a class derived from a given base class, you could use:

bar_instance = Bar()
print issubclass(bar_instance.__class__, Foo)
0

精彩评论

暂无评论...
验证码 换一张
取 消