Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I check (at runtime) if one class is a subclass of another?

People also ask

Is there a way to check if a class is a subclass of another class?

Python issubclass() is built-in function used to check if a class is a subclass of another class or not. This function returns True if the given class is the subclass of given class else it returns False . Return Type: True if object is subclass of a class, or any element of the tuple, otherwise False.

Does Isinstance check subclass?

isinstance() is used to check if an object is an instance of a certain class or any of its subclass. Again, issubclass() is used to check if a class type is the subclass of a different class.

How do you check if a class inherits from another Java?

If you want to know whether or not a Class extends another, use Class#isAssignableFrom(Class). For your example, it would be: A obj = new A(); if(obj instanceof B) { ... } If you want to check for direct superclass/subclass relationships, Tim has provided an answer as well.


You can use issubclass() like this assert issubclass(suit, Suit).


issubclass(class, classinfo)

Excerpt:

Return true if class is a subclass (direct, indirect or virtual) of classinfo.


You can use isinstance if you have an instance, or issubclass if you have a class. Normally thought its a bad idea. Normally in Python you work out if an object is capable of something by attempting to do that thing to it.


The issubclass(sub, sup) boolean function returns true if the given subclass sub is indeed a subclass of the superclass sup.


issubclass minimal runnable example

Here is a more complete example with some assertions:

#!/usr/bin/env python3

class Base:
    pass

class Derived(Base):
    pass

base = Base()
derived = Derived()

# Basic usage.
assert issubclass(Derived, Base)
assert not issubclass(Base, Derived)

# True for same object.
assert issubclass(Base, Base)

# Cannot use object of class.
try:
    issubclass(derived, Base)
except TypeError:
    pass
else:
    assert False

# Do this instead.
assert isinstance(derived, Base)

GitHub upstream.

Tested in Python 3.5.2.


You can use the builtin issubclass. But type checking is usually seen as unneccessary because you can use duck-typing.