Python class 创建前键入用法

Python class type usage before created

我需要 class 在 class 方法范围内创建其他 class 实例和自身实例的可能性。我有以下代码:

class A:
    #somme stuff

class B:
    allowed_children_types = [ #no reason to make self.allowed_children_types
        A,
        C #first problem, no C know
    ]

    @staticmethod
    def foo(self):
        #use allowed_children_types to create children objects


class C:
    allowed_children_types = [  # no reason to make self.allowed_children_types
        A,
        B
        C  # second problem, no C know because type object is not yet created
    ]

    @staticmethod
    def foo(self):
        #use allowed_children_types to create children objects

我不会创建独立工厂,因为它会使非常简单的应用程序逻辑复杂化。我觉得创建自定义 metaclass 通常是糟糕的设计。

我应该怎么做才能跳过这个问题?

您必须先定义所有这些名称,然后才能使用它们。类似于:

class A:
    #somme stuff

class B:

    @staticmethod
    def foo(self):
        #use allowed_children_types to create children objects


class C:

    @staticmethod
    def foo(self):
        #use allowed_children_types to create children objects

B.allowed_children_types = [A, C]
C.allowed_children_types = [A, B, C]