Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 lots 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 can not be inherited from each other, since it does not make sense.

What I have in mind, is just to combine all methods into a super big class. But I don't feel this is a right way to do it.

like image 397
hans-t Avatar asked Mar 03 '15 11:03

hans-t


1 Answers

You are correct, in your case inheritance does not make sense. But, how about explicitly passing the objects during the instantiation. This would make a lot of sense.

Something like:

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

While instantiating, do:

objA = BigClassA()
..
objB = BigClassB(objA)
..
objC = BigClassC(objA, objB)
like image 55
UltraInstinct Avatar answered Nov 10 '22 00:11

UltraInstinct