Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test an object class inherit from a certain abstract class

In Python when you want to test that an object foo is an instance of Foo you do this :

if isinstance(foo, Foo):
    # do something

Now, imagine that Foo class is a specialized class inherited from Bar and that there is a lot of other classes that inherit from it: I've Foo1, Foo2, ..., FooX, that inherit from Bar class.

foo could be an instance from any of these Foox class. What's interest me is to know that foo come from a class that inherited one day from Bar. Did you know a simple / canonical way to do it ?

like image 543
snoob dogg Avatar asked Sep 12 '25 03:09

snoob dogg


1 Answers

The correct approach is probably to test if foo is a Bar object, which shows that Foo inherited from Bar.

class Bar:
    pass

class Foo(Bar):
    pass

foo = Foo()

isinstance(foo, Bar)

output:

True

You could also check if the class Foo is a subclass of the class Bar:

issubclass(Foo, Bar)   # notice Foo, the class, not the instance foo
like image 65
Reblochon Masque Avatar answered Sep 13 '25 18:09

Reblochon Masque