【发布时间】: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