在类之间传输变量

时间:2010-12-31 18:07:02

标签: python class variables class-variables

我有2个类在相同的变量上运行,但彼此相反。有没有办法在它们之间传输变量而无需对每个交换进行硬编码或将所有值组合成一个数组?组合这些课程不是一种选择。

#pseudocode

class class1:
   def __init___(self):
      # code
      initialize variable MAIN

   # do stuff
   # do stuff
   make variable stuff
   # do stuff
   make variable thing
   # do stuff

class class2:
   def __init___(self):
      # code
      initialize variable stuff
      initialize variable thing
   # do stuff
   # do stuff
   undo variable stuff
   # do stuff
   undo variable thing
   # do stuff
   make variable MAIN

我希望能够快速在class1class2之间来回发送数据。

2 个答案:

答案 0 :(得分:2)

将共享数据放入第三个对象并从两个类中引用它。

答案 1 :(得分:2)

我认为这比你想象的容易得多。以下是两个类之间“发送”数据的一些示例。

class class2(object):
    def __init__(self, other):
        self.other = other

    def set_color(self, color):
        self.color = color
        # "Sending" to other class:
        self.other.color = color

    def set_smell(self, smell, associated_object):
        self.smell = smell
        associated_object.smell = smell

这样的用法:

>>> ob1 = class1()
>>> ob2 = class2(ob1)
>>> ob2.set_color("Blue")
>>> ob1.color
"Blue"

>>> ob2.set_smell("Good", ob1)
>>> ob1.smell
"Good"
相关问题