在类之间传递变量

发布于 2024-10-10 01:30:44 字数 620 浏览 3 评论 0原文

我有两个类对相同的变量进行操作,但彼此相反。有没有一种方法可以在它们之间传输变量,而无需对每次交换进行硬编码或将所有值组合到一个数组中?合并这些类不是一个选择。

#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 之间快速来回发送数据。

I have 2 classes that operate on the same variables but do the inverse of each other. Is there a way to transfer the variables between them without hard coding every exchange or combining all the values into one array? Combining the classes is not an option.

#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

I want to be able to send data back and forth between class1 to class2 quickly.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

送你一个梦 2024-10-17 01:30:44

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

Put the shared data into a third object and reference it from both classes.

2024-10-17 01:30:44

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

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"

I think this is much easier than you think. Here is some examples of "sending" data between two classes.

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

Usage like this:

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

>>> ob2.set_smell("Good", ob1)
>>> ob1.smell
"Good"
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文