Martin DeMello
Martin DeMello

Reputation: 12336

What is the issubclass equivalent of isinstance in python?

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?

Upvotes: 8

Views: 6623

Answers (1)

ChristopheD
ChristopheD

Reputation: 116137

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)

Upvotes: 22

Related Questions