简体   繁体   English

如何使界面与转换一起工作

[英]How can I make an interface work with casting

So, I am programming my Python Program with the MVC-Architecture, and I want everything nice and seperated from each other. 所以,我正在使用MVC-Architecture编写我的Python程序,我希望一切都很好并且彼此分离。 I don't want the View of my GUI having to work with the Controllers instance and so on. 我不希望我的GUI视图必须使用Controllers实例等等。 So I made an 'IController' abstract class which is the parent of 'Controller', which has all of the functions. 所以我创建了一个'IController'抽象类,它是'Controller'的父级,它具有所有的功能。 In 'IController' I have the functions my Model and View need to access. 在'IController'中,我有我的模型和视图需要访问的功能。 The Controller looks somewhat like this: Controller看起来有点像这样:

class IController:
     def method(self):
          pass

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

So where I previously had 所以我以前在那里

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

I now want to turn this into 我现在想把它变成

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

The problem here is, that when I do this, I can't keep the instance of my 'Controller' Class. 这里的问题是,当我这样做时,我无法保留我的'Controller'类的实例。 I need this, since the instance has values and methods I need to work with here. 我需要这个,因为实例具有我需要在这里使用的值和方法。 I also can't save the instance of 'Controlle'r in 'IController' since it is an abstract class, so I won't instance it and can't save anything in it. 我也无法在'IController'中保存'Controlle'r的实例,因为它是一个抽象类,所以我不会实例化它并且不能保存它。

I expected it to just work, but I am not sure if this is possible now. 我希望它能够正常工作,但我不确定现在是否可行。 I read that casting is not possible in python, but I think there must be another way for me to fix this. 我知道在python中不可能进行转换,但我认为必须有另一种方法来解决这个问题。 When I ran it, it told me that I am lacking 'self'. 当我跑它时,它告诉我,我缺乏'自我'。 I can't send the instance of the Controller with it, then it would not be capsulated. 我不能用它发送Controller的实例,然后它不会被封装。 Is there a way around this? 有没有解决的办法?

For other people who might try the same: It is not possible to do this like you would do it in C# or others. 对于可能尝试相同的其他人:不可能像在C#或其他人那样做这样做。 I solved it by re-writing my program in and learning C#. 我通过重新编写程序并学习C#来解决它。 That and some ugly workarounds are the only possibilities. 这和一些丑陋的解决方法是唯一的可能性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM