首页 > 解决方案 > 如何使界面与铸造一起使用

问题描述

因此,我正在使用 MVC 架构编写我的 Python 程序,并且我希望一切都很好并且彼此分开。我不希望我的 GUI 视图必须与控制器实例等一起工作。所以我做了一个'IController'抽象类,它是'Controller'的父类,它具有所有的功能。在“IController”中,我有我的模型和视图需要访问的功能。控制器看起来有点像这样:

class IController:
     def method(self):
          pass

class Controller(IController):
     self.x = 'Hello'
     def method(self):
          print('self.x)

所以我以前有

class Frame(tk.Frame):
    def __init__ (self, controller):
            self.controller = controller
    button = tk.Button(self, command=lambda: self.controller.method()

我现在想把它变成

class Frame(tk.Frame):
    def __init__ (self, controller):
            self._controller = type(controller)
    button = tk.Button(self, command=lambda: self._controller.method()

这里的问题是,当我这样做时,我无法保留我的“控制器”类的实例。我需要这个,因为该实例具有我需要在这里使用的值和方法。我也无法在 'IController' 中保存 'Controlle'r 的实例,因为它是一个抽象类,所以我不会实例化它,也无法在其中保存任何内容。

我希望它能够正常工作,但我不确定现在是否可行。我读到在 python 中无法进行强制转换,但我认为必须有另一种方法来解决这个问题。当我运行它时,它告诉我我缺乏“自我”。我不能用它发送控制器的实例,那么它就不会被封装。有没有解决的办法?

标签: pythonpython-3.xclassoopcasting

解决方案


对于可能尝试相同的其他人:不可能像在 C# 或其他语言中那样执行此操作。我通过用 C# 重写程序和学习 C# 解决了这个问题。那和一些丑陋的解决方法是唯一的可能性。


推荐阅读