Python 使用循环引用

Python working with circular references

我在循环引用方面遇到了麻烦。有时它的工作有时不是。我是编程新手,这里有些东西我不明白。

看看这段代码。

图形用户界面模块:

import gi
gi.require_version('Gtk', '3.0')
import task as task
from gi.repository import Gtk


class Window(Gtk.Window):

    def __init__(self):
        Gtk.Window.__init__(self, title="Avoid C R")

        self.main_box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL,
                                spacing=10)

        self.question = Gtk.Label("what is your name ?")
        self.answer = Gtk.Entry()
        self.button = Gtk.Button(label="Use fonction in another module")

        self.add(self.main_box)
        self.main_box.pack_start(self.question, True,True, 0)
        self.main_box.pack_start(self.answer, True, True, 0)
        self.main_box.pack_start(self.button, True, True, 0)

        self.button.connect("clicked", self.button_clicked)

    def button_clicked(self, widget):
        task.print_name()

win = Window()
win.connect("delete-event", Gtk.main_quit)
win.show_all()
Gtk.main()

模块任务:

import gui as gui


def print_name():
    x = gui.win.answer.get_text()
    print("Name is ", x)

我已经有 10 000 行代码使用这种模式并且运行良好。我每天都用它。

但现在我尝试用相同的模式重写我的代码,但它不再起作用了。我很确定这是循环引用的问题。

我的问题是 « 如果我有相当大的应用程序并且我想使用很多模块:避免循环引用的正确方法是什么? »

您可以将 window 传递给 print_name。现在您可以删除模块引用,它可以被许多程序用来引导。

task.py:

def print_name(gui):
    x = gui.win.answer.get_text()
    print("Name is ", x)