Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define type 'a child class of' in python?

In the following example, the list1 attribute of P represents a list of instances of A.

class A:
   value1: str

class B(A):
   value2: str

class P:
   list1: List[A]

I want is to keep a list of child classes of A (not instances of A) in the variable list1. Is there a way to do it in python?

like image 583
Janaka Chathuranga Avatar asked Nov 17 '25 14:11

Janaka Chathuranga


1 Answers

The solution is to use https://docs.python.org/3/library/typing.html#typing.Type.

from typing import List, Type

class P:
   list1: List[Type[A]]

Now, list1 represents a list of classes extended from A.

like image 74
Janaka Chathuranga Avatar answered Nov 19 '25 03:11

Janaka Chathuranga



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!