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

后端 未结 1 893
暖寄归人
暖寄归人 2020-12-31 15:15
    Class BigClassA:
        def __init__(self):
            self.a = 3
        def foo(self):
            self.b = self.foo1()
            self.c = self.foo2()
             


        
相关标签:
1条回答
  • 2020-12-31 15:35

    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)
    
    0 讨论(0)
提交回复
热议问题