创建前的 Python 类类型使用

Posted

技术标签:

【中文标题】创建前的 Python 类类型使用【英文标题】:Python class type usage before created 【发布时间】:2021-04-01 05:17:00 【问题描述】:

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

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

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

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

【问题讨论】:

您只能引用已定义的名称。分类定义后,分配类变量 听起来像XY problem。请提供有关您实际想要做什么的信息。为什么不能使用classmethod 【参考方案1】:

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

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]

【讨论】:

肮脏的解决方案(我想要更干净的解决方案)但对我来说已经足够了。

以上是关于创建前的 Python 类类型使用的主要内容,如果未能解决你的问题,请参考以下文章

启动对象时类类型前的反斜杠[重复]

使用仿函数时,括号前的表达式必须具有指向函数的类型

python中int是啥意思

Python 函数前的下划线

Python 函数前的下划线

Python进阶开发之元类编程