循环依赖 python 用于同一文件中的函数



我的代码结构是这样的:-

def send_message(msg):
    print msg + "n"
    x.new_message("You",msg)

class GUI(Frame):
def createWidgets(self):
    self.input.bind('<Key-Return>',self.send)
def send(self, event):
    send_message(self.contents.get())
    self.contents.set("")
def new_message(self,sender, msg):
    line = sender+": "+msg+"n"
    self.chat.contents.set(self.chat.contents.get()+line)
def __init__(self):
    self.createWidgets()
x = GUI()

如您所见,这有一些循环依赖关系。功能send_message需要实例 x 以及 GUI new_message方法。GUI 定义需要send_message。因此,不可能满足所有约束。怎么办?

在 die 注释中显示的完整代码中,我们可以看到您在 GUI.__init__ 中调用了 self.mainloop()。这将启动 gui 的事件处理,并且可能不会在程序完成之前终止。只有这样,作业x = GUI()才会完成,x才可用。

要避免这种情况,您有多种选择。一般来说,在__init__中做一个无限循环可能是一个坏主意。而是在实例化 GUI 后调用mainloop()

def __init__(self):
    # only do init
x = GUI()
x.mainloop()

正如 jasonharper 在 python 中所说,函数中的变量只有在执行该函数时才会被查找,而不是在定义它们时。因此,运行时中的循环依赖在大多数情况下在 python 中不是问题。

Python 函数

中的名称在定义函数时不需要引用任何内容 - 只有在实际调用函数时才会查找它们。 因此,您的send_message()完全没问题(尽管最好将x作为参数而不是全局变量(。

您的GUI类将无法如图所示进行实例化,因为引用了您没有显示创建的小部件 - 例如self.input。 我不知道其中有多少是由于您剥离代码以进行发布。

最新更新