Python: 不同类实例之间如何共享数据?

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

问题: 基本上我有 3 个 classes 和很多方法,正如您从代码中看到的那样,它们有些依赖。如何将实例变量 self.b、self.c、self.d 的值从 BigClassA 共享到 BigClassB?

nb: 这3个class不能相互继承,因为没有意义。

我的想法,就是把所有的方法组合成一个超大的class。但我觉得这不是正确的做法。

你是对的,在你的情况下继承没有意义。但是,如何在实例化期间显式传递对象。这很有意义。

类似于:

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)