简体   繁体   English

如何通过多变量依赖注入连接不同类的变量?

[英]How connect variables of different classes with mutliple dependency injection?

I'm trying to make dependency injection to connect two classes together. 我正在尝试进行依赖注入以将两个类连接在一起。 For instance with the below code: 例如下面的代码:

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

class one() has the property 'a' of class two() and class two() has the property b of class one() . class one()具有class two()的属性'a',class two()具有class one()的属性b But obviously I get an error from the line self.C_one = one() in class three() because I don't know self.C_two yet. 但是很明显,我在类three() self.C_one = one()行中self.C_one = one()了错误,因为我还不知道self.C_two How can I create reciprocal link between two classes like in my example? 如何像我的示例那样在两个类之间创建相互链接?

if one needs a two and two needs a one then your only solution is to use a two-stages initialisation of either one or two : 如果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

but it's still a probable design smell... 但这仍然是可能的设计气味...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM