【发布时间】:2012-01-09 13:35:55
【问题描述】:
我有一个基类,它有一个创建子类实例的方法,该子类的调用与输入字符串相同。
这在以前通过将子类和基类放在同一个文件中并执行类似globals()[name] 的操作来实现。
不过,现在我已将子类拆分为其他文件。它们每个顶部都有一个import base 语句,所以我不能简单地在我的基类中导入子类,否则会有一个循环导入链。
有什么解决方法吗?
在 base.py 中:
from basefactory import BaseFactory
class Base:
def __init__(self, arg1, arg2):
...
def resolve(self, element):
className = typing.getClassName(element)
return BaseFactory.getInstance(className, element, self)
在 basefactory.py:
from file1 import *
from file2 import *
...
class BaseFactory:
@staticmethod
def getInstance(name, arg1, arg2):
subclass = globals()[name]
return subclass(arg1, arg2)
在file1.py中:
from base import Base
class subclass1(Base):
def foo(self):
return self.arg1
【问题讨论】:
-
resolve() 是否只是为了确定类类型,并返回一个新的自身实例?
-
它返回一个 Base 子类的实例。
-
将resolve移入负责返回正确实例的工厂类怎么样?
标签: python inheritance import subclass base