Python类不断地互相调用

2024-03-28 19:13:46 发布

您现在位置:Python中文网/ 问答频道 /正文

我一直在尝试为我的两个文件使用类。我做了一个gui.py:

class GuiStart:    
    def __init__(self, master):
        self.master = master
        self.master.title("DECTools 1.3")

我有另一个文件,其中包含要执行的方法。此文件名为foo.py

class DecToolsClass:
    def __init__(self):
        self.gui = gui.GuiStart()

我得到一个错误,因为我没有给它主参数。我无法将其设置为“无”,因为它没有.title方法

我使用以下命令执行gui文件:

if __name__ == "gui":
    root = tkinter.Tk()
    my_gui = GuiStart(root)
    root.mainloop()

问题是我需要使用gui.py文件从foo.py执行一个方法,并且需要使用foo.py文件从gui.py文件访问属性。我一直在努力实现这一点,我知道我不能像Java那样使用多个构造函数

有可能是我想要的还是我必须重写我的代码

提前谢谢


Tags: 文件方法pyselfmasterfootitleinit
1条回答
网友
1楼 · 发布于 2024-03-28 19:13:46

The GuiStart class starts the tkinter gui. The window with buttons and entries is created with that class. From the GuiStart class I call methods that do things like copy files to a certain location

好吧,总结一下,你有一个处理用户交互的类,还有一组不做用户交互的泛型方法,GuiStart提供了一个Gui。如果我理解错了,这个答案就没什么用了

将它们分开确实是一个好主意,但是要使这种分开有效,您不能有彼此的直接引用。这意味着这是一个明确的不要:

class DecToolsClass:
    def __init__(self):
        self.gui = gui.GuiStart()

如果您真的需要这些工具来访问gui,您可以将其注入。但通常情况下,您会希望它反过来:工具应该是通用的,而不了解Gui。另一方面,Gui知道它们。假设其余代码是正确的(我不知道tkinter):

def main():
    tools = DecToolsClass()  # not shown, but it no longer has self.gui

    root = tkinter.Tk()
    my_gui = gui.GuiStart(root, tools)
    root.mainloop()

if __name__ == '__main__':
    main()

这当然意味着GuiStart必须使用它将用作参数的工具集:

class GuiStart:    
    def __init__(self, master, tools):
        self.master = master
        self.master.title("DECTools 1.3")
        self.tools = tools

现在,在GuiStart的任何地方,任何工具的使用都必须经过self.tools。作为额外的好处,在unittests中,您可以传递一个虚拟的tools对象,它只检查如何调用它,这使得测试非常容易

相关问题 更多 >