1

At runtime, I want to check whether a specified child class is derived from a specified parent class.

With an object instance, it's easy:

def is_related(child_instance, parent_type):
    return isinstance(child_instance, parent_type)

Is there some way to do this without having (or creating) an instance of the child but, instead, having a reference to the child's type?

Something like...

def is_related(child_type, parent_type):
    return is_child_class(child_type, parent_type)

Provide an implementation for is_child_class will answer this question.

(By comparison, types in C# know about their supertypes. I don't know whether this is also true in Python.)

Eric McLachlan
  • 3,132
  • 2
  • 25
  • 37
  • 2
    Does this answer your question? [How do I check (at runtime) if one class is a subclass of another?](https://stackoverflow.com/questions/4912972/how-do-i-check-at-runtime-if-one-class-is-a-subclass-of-another) – Riccardo Bucco Dec 05 '19 at 11:38

3 Answers3

2

Let's say that ChildClass is a subclass of ParentClass. Then

issubclass(ChildClass, ParentClass)

would return True

Riccardo Bucco
  • 13,980
  • 4
  • 22
  • 50
mcsoini
  • 6,280
  • 2
  • 15
  • 38
2

Here is a possible solution:

class A:
    pass

class B(A):
    pass

issubclass(B, A) # True
Riccardo Bucco
  • 13,980
  • 4
  • 22
  • 50
2

This is what you need to define the is_child_class method as:

def is_child_class(child_type, parent_type):
  return issubclass(child_type, parent_type)
Eb J
  • 183
  • 1
  • 10