对象之间如何交换信息?

问题描述 投票:0回答:1

我有一个类 (my_class),它实例化另一个类 (xpto) 并执行一个方法 (connect);当此方法完成时,它会触发一个事件 (on_connect),我想在“my_class”中了解它。我该怎么做 ? - 谢谢

class my_class():
    xpto = another_class()
    xpto.connect()
    ' if connection ok print a msg
    .....


class another_class()
    def connect():
        ....
        code follows and an event id fired is succeeded (on_connect)

    on_connect():
        ' here I would like to notify my_class the connection was ok and i do not know how to do it  

我尝试了不同的方法但没有成功,大多数时候收到与“循环导入”相关的错误。 谢谢

python instance
1个回答
0
投票

是否可以简单地将

my_class
'实例传递给其他类?

class my_class():
    def __init__(self):
        self.xpto = another_class(self)
        self.xpto.connect()

    def on_connection_success(self):
        print("Connection succeeded.")

class another_class():
    def __init__(self, my_class_instance):
        self.my_class_instance = my_class_instance

    def connect(self):
        if connection_succeeded:
            self.on_connect()

    def on_connect(self):
        self.my_class_instance.on_connection_success()
© www.soinside.com 2019 - 2024. All rights reserved.