在类之间传递变量

1 投票
2 回答
1407 浏览
提问于 2025-04-16 09:15

我有两个类,它们处理的是相同的变量,但它们的操作是相反的。有没有什么方法可以在这两个类之间传递变量,而不需要每次都手动写出每个交换的内容,也不想把所有的值放到一个数组里?合并这两个类也不是一个选项。

#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 个回答

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"
2

把共享的数据放到一个第三个对象里,然后让两个类都去引用这个对象。

撰写回答