Search code examples
pythonclassattributesdependenciesself-reference

Dependencies between attributes of 2 and more classes


Is it possible to initialize instances of classes with attributes that are dependent across (not in circular way)?

Today, I use dictionaries instead of classes as follows:

dictA = {'A1': 10}
dictB = {'B1': 2}
dictB['B2'] = dictA['A1'] * dictB['B1']
dictA['A2'] = dictB['B2'] * 3  # dictA['A1'] * dictB['B1'] * 3

print(dictA)  # {'A1': 10, 'A2': 60}
print(dictB)  # {'B1': 2, 'B2': 20}

When I try to express the above with classes, I end up with RecursionError: maximum recursion depth exceeded.

class A:
    def __init__(self):
        self.A1 = 10
        self.A2 = B().B2 * 3

class B:
    def __init__(self):
        self.B1 = 2
        self.B2 = self.B1 * A().A1
    
a = A()
b = B()

The dictionaries (classes) are separate because they represent different types of data (e.g. employees and time).


Solution

  • You need to make the initializers non-circular. Then you can use @property to lazily evaluate the properties

    class A:
        def __init__(self):
            self.A1 = 10
    
        @property
        def A2(self):
            return B().B2 * 3
    
    
    class B:
        def __init__(self):
            self.B1 = 2
    
        @property
        def B2(self):
            return self.B1 * A().A1
    
    
    a = A()
    b = B()
    
    print(a.A1, a.A2, b.B1, b.B2)
    

    Result:

    10 60 2 20