2015-03-03 103 views
4
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?Python:如何在不同类的实例之间共享数据?

nb:这3个类不能彼此继承,因为它没有意义。

我想到的只是将所有方法合并为一个超级大类。但我不认为这是一个正确的方式来做到这一点。

+0

'类BigClassB(BigClassA):'和'类BigClassC(BigClassA,BigClassB)'。使用继承 – ForceBru 2015-03-03 11:50:00

+1

您可以尝试使用构图。那就是当你在B类的一个实例中实例化一个类A的对象时。这样你就可以拥有连接,而不用说其中的一个是专门化的。 [阅读](http://learnpythonthehardway.org/book/ex44.html)。除此之外,您可以发送类A的对象并将您需要的属性分配给类B中的新属性。尽管这可能会破坏数据一致性。 – ljetibo 2015-03-03 11:50:07

+0

你想分享每个班级的实例还是全球的数据? – 2015-03-03 11:50:36

回答

5

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

喜欢的东西:

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) 
+0

有趣的是,这是什么样的设计或模式?这是常见的事情,还是有更好的方法来解决问题? – 2015-03-03 11:59:28

+1

@ user74158即使有名字也可能太常见了。 – 2015-03-03 12:09:21

+1

@ user74158这不是设计模式或任何东西。它只是实现你想要做的事情的一种标准手段。这个想法是通过将依赖对象传递给'__init__'来建立显式依赖关系。 – SuperSaiyan 2015-03-03 12:10:58