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

时间:2015-03-03 11:47:30

标签: python class instance-variables

    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个类,有很多方法,从代码中可以看出它们有点依赖。如何将BigClassA中的实例变量self.b,self.c,self.d的值共享到BigClassB?

nb:这三个类不能相互继承,因为它没有意义。

我想到的是将所有方法组合成一个超级大班。但我不觉得这是一种正确的做法。

1 个答案:

答案 0 :(得分:6)

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

类似的东西:

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)