假设我有以下基数和子项
class Base:
def __new__(cls, *args):
if cls is Base:
if len(args) < 2:
return Child1.__new__(Child1, *args)
return Child2.__new__(Child2, *args)
return super().__new__(cls)
def __init__(self, arg):
self.common_arg = arg
class Child1(Base):
def __init__(self, arg0=None):
super().__init__(arg0)
class Child2(Base):
def __init__(self, arg0, arg1, *args):
super().__init__(arg0 + arg1)
self.args = list(args).copy()
显然,这些类之间存在循环依赖关系,但是,只要所有类都在同一模块中定义,就不会引起任何问题。
现在,如何将它们分成三个模块(在同一包装中?)>
我将其分成三个文件:
package/ __init__.py base.py ch1.py ch2.py
具有以下内容:
# base.py ############################################################ from . import ch1, ch2 class Base: def __new__(cls, *args): if cls is Base: if len(args) < 2: return ch1.Child1.__new__(ch1.Child1, *args) return ch2.Child2.__new__(ch2.Child2, *args) return super().__new__(cls) def __init__(self, arg): self.common_arg = arg # ch1.py ############################################################ from . import base class Child1(base.Base): def __init__(self, arg0=None): super().__init__(arg0) # ch2.py ############################################################ from . import base class Child2(base.Base): def __init__(self, arg0, arg1, *args): super().__init__(arg0 + arg1) self.args = list(args).copy()
按照建议的here,但它不起作用。
import package.ch1
提高
AttributeError: module 'package.base' has no attribute 'Base'
假设我具有以下基类和子类Base:def __new __(cls,* args):如果cls是Base:if len(args)<2:返回Child1 .__ new __(Child1,* args)...
让您的用户调用工厂功能: