【问题标题】:How connect variables of different classes with mutliple dependency injection?如何使用多个依赖注入连接不同类的变量?
【发布时间】:2017-12-18 20:55:20
【问题描述】:

我正在尝试进行依赖注入以将两个类连接在一起。 例如下面的代码:

class one():
    def __init__(self,two):
        self.b = 0
        self.C_two = two

    def compute(self):
        print(self.a)
        self.b = self.b + 1

    @property
    def a(self):
        return self.C_two.a


class two():
    def __init__(self,one):
        self.a = 0
        self.C_one = one

    def compute(self):
        self.a = self.a + 1

    @property
    def b(self):
        return self.C_one.b

class three():
    def __init__(self):
        self.C_one = one()
        self.C_two = two(self.C_one)
        self.b = 0

    def compute(self):
        self.C_one.compute()
        print('C_one a=',self.C_one.a )
        print('C_two a=',self.C_two.a )

C_three = three()
for i in range(5):
    C_three.compute()

one() 类具有two() 类的属性“a”,two() 类具有one() 类的属性b。但显然我在three() 类中的self.C_one = one() 行中收到错误,因为我还不知道self.C_two。如何在我的示例中创建两个类之间的互惠链接?

【问题讨论】:

    标签: python class dependency-injection dependencies


    【解决方案1】:

    如果one 需要twotwo 需要one,那么您唯一的解决方案是使用onetwo 的两阶段初始化:

    class three():
        def __init__(self):
            self.C_one = one(None)
            self.C_two = two(self.C_one)
            self.C_one.two = self.C_two
    

    但这仍然是一种可能的设计气味......

    【讨论】:

    • 好的,那我就用那个。谢谢
    猜你喜欢
    • 1970-01-01
    • 2014-01-02
    • 1970-01-01
    • 2011-12-19
    • 2014-05-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-25
    相关资源
    最近更新 更多