Python: how to share data between instances of different classes?

    Class BigClassA:
        def __init__(self):
            self.a = 3
        def foo(self):
            self.b = self.foo1()
            self.c = self.foo2()
            self.d = self.foo3()
        def foo1(self):
            # do some work using other methods not listed here
        def foo2(self):
            # do some work using other methods not listed here
        def foo3(self):
            # do some work using other methods not listed here

    Class BigClassB:
        def __init__(self):
            self.b = # need value of b from BigClassA
            self.c = # need value of c from BigClassA
            self.d = # need value of d from BigClassA
        def foo(self):
            self.f = self.bar()
        def bar(self):
            # do some work using other methods not listed here and the value of self.b, self.c, and self.d


    Class BigClassC:
        def __init__(self):
            self.b = # need value of b from BigClassA
            self.f = # need value of f from BigClassB
        def foo(self):
            self.g = self.baz()
        def baz(self):
            # do some work using other methods not listed here and the value of self.b and self.g

Question: Basically, I have 3 classes with a lot of methods, and they are somewhat dependent, as you can see from the code. How do I share the value of instance variables self.b, self.c, self.d from BigClassA to BigClassB?

nb: these 3 classes cannot be inherited from each other, as this does not make sense.

What I mean is simply to combine all the methods into a super large class. But I do not think that this is the right way to do this.

+4
source share
1 answer

You are right, in your case inheritance does not make sense. But, how about the explicit transfer of objects during creation. That will make a lot of sense.

- :

Class BigClassA:
    def __init__(self):
        ..
Class BigClassB:
    def __init__(self, objA):
        self.b = objA.b
        self.c = objA.c
        self.d = objA.d

Class BigClassC:
    def __init__(self, objA, objB):
        self.b = objA.b # need value of b from BigClassA
        self.f = objB.f # need value of f from BigClassB

:

objA = BigClassA()
..
objB = BigClassB(objA)
..
objC = BigClassC(objA, objB)
+5

All Articles