如何导入包含具有循环依赖关系的类的模块?

时间:2020-02-11 13:52:28

标签: python python-3.x python-module

假设我有以下基数和子级

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()   

如建议的enter image description here,但不起作用。

import package.ch1

提高

AttributeError: module 'package.base' has no attribute 'Base'

1 个答案:

答案 0 :(得分:0)

让您的用户调用工厂功能:

library(ggplot2)
example3 <- function(x){
  data.frame(
    x = x,
    sin = sin(x),
    cos = cos(x)
  )
}

x_grid=seq(0,1,0.05)
ggplot(data = example3(x_grid),
       aes(x=x)) +
  geom_line(aes(y = sin), color = "blue") +
  geom_line(aes(y = cos), color = "red")

现在,上述代码的每个部分都可以拆分成自己的文件。

相关问题