Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
691 views
in Technique[技术] by (71.8m points)

class - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...