【问题标题】:Python class type usage before created创建前的 Python 类类型使用
【发布时间】: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

标签: python python-3.x class types metaclass


【解决方案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]

【讨论】:

  • 肮脏的解决方案(我想要更干净的解决方案)但对我来说已经足够了。
猜你喜欢
  • 2012-06-27
  • 2013-05-16
  • 1970-01-01
  • 1970-01-01
  • 2021-05-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多