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

2024-10-01 07:32:01 发布

您现在位置: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?在

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

我的想法是,将所有方法组合成一个超级大类。但我觉得这样做不对。在


Tags: ofselfherevaluedefnotsomeneed
1条回答
网友
1楼 · 发布于 2024-10-01 07:32:01

你是对的,在你的情况下继承是没有意义的。但是,在实例化过程中显式地传递对象怎么样。这很有意义。在

比如:

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

实例化时,请执行以下操作:

^{pr2}$

相关问题 更多 >