简体   繁体   中英

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

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...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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