如何在python中定义类型'a child class of'?

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

在下面的示例中,Plist1 属性表示 A 的实例列表。

class A:
   value1: str

class B(A):
   value2: str

class P:
   list1: List[A]

我想要在变量 list1 中保留 A 的子 类 的列表(不是 A 的实例)。 python 有办法吗?

...
class P:
    A.__subclasses__()

>>> [<class '__main__.B'>, <class '__main__.C'>, <class '__main__.D'>]

sub类 - Returns 直接继承自这个 类 的弱引用列表。 enter link description here

我尝试从这里的第一个答案复制 :How to find all the subclasses of a class given its name? :

class klass():
    pass



class popo(klass):
    pass

class pepe(klass):
    pass



class P():
    

    def get_all_subclasses(self, cls):
        subclass_list = []
    
        def recurse(classe):
            for subclass in classe.__subclasses__():
                subclass_list.append(subclass)
                recurse(subclass)
    
        recurse(cls)
    
        return list(set(subclass_list))

a = P()


print(a.get_all_subclasses(klass),'\n')

print(type(a.get_all_subclasses(klass)),'\n')


class papa(klass):
    pass

class coco(popo):
    pass


print(a.get_all_subclasses(klass),'\n')

输出:

[<class '__main__.popo'>, <class '__main__.pepe'>] 

<class 'list'> 

[<class '__main__.papa'>, <class '__main__.popo'>, <class '__main__.pepe'>, <class '__main__.coco'>] 

或:

class klass:
    pass


class popo(klass):
    pass


class pepe(klass):
    pass


class P:
    def __init__(self, classez):
        self.list1 = []

        self.get_all_subclasses(classez)

        pass

    def get_all_subclasses(self, cls):
        def recurse(classe):
            for subclass in classe.__subclasses__():
                self.list1.append(subclass)
                recurse(subclass)  # necessarioo per avere coco nella lista

        recurse(cls)

        self.list1 = list((self.list1))

        return self.list1


a = P(klass)

print(a.list1, "\n")

print(type(a.list1), "\n")


class papa(klass):
    pass


class coco(popo):
    pass


a = P(klass)


print(a.list1)

我也明白了:

[<class '__main__.popo'>, <class '__main__.pepe'>] 

<class 'list'> 

[<class '__main__.popo'>, <class '__main__.coco'>, <class '__main__.pepe'>, <class '__main__.papa'>]

使用:

class klass():
    pass



class popo(klass):
    pass

class pepe(klass):
    pass


print(klass.__subclasses__(),'\n')



class papa(klass):
    pass

class coco(popo):
    pass


print(klass.__subclasses__(),'\n')

我得到:

[<class '__main__.popo'>, <class '__main__.pepe'>] 

[<class '__main__.popo'>, <class '__main__.pepe'>, <class '__main__.papa'>] 

解决方法是使用https://docs.python.org/3/library/typing.html#typing.Type.

from typing import List, Type

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

现在,list1 表示从 A.

扩展的 类 列表