Python:如何在不同类的实例之间共享数据? [英] Python: How to share data between instances of different classes?

查看:209
本文介绍了Python:如何在不同类的实例之间共享数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

    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个类,有很多方法,它们在某种程度上是依赖于您可以从代码中看到。我如何共享实例变量self.b,self.c,self.d从BigClassA到BigClassB的值?

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:这3个类不能从继承

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.

推荐答案

您是正确的,在您的情况下继承不会有道理。但是,如何在实例化期间显式传递对象。

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.

类似的东西:

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)

这篇关于Python:如何在不同类的实例之间共享数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆