Python类间变量共享问题排查与Controller模式实践
Python类间变量共享问题及Controller模式解决方案
我查了很多关于类变量(class variable)和实例变量(instance variable)的资料,还是搞不懂怎么在Python的类之间共享变量。下面是我写的PyQt5代码示例:
#!/usr/bin/python3 from PyQt5.QtWidgets import (QApplication) import sys class One(): def __init__(self, myTextString, parent=None): self.mytext = myTextString self.printtxt() Main.txt = 'another string' self.txt2 = 'a third string' def printtxt(self): print('One',self.mytext) class Two(): def __init__(self, parent=None): self.printtxt() def printtxt(self): print('Two',One.txt) # Attribute Error print('Two',One.txt2) # Attribute Error class Main(): def __init__(self, parent = None): self.txt = 'a string of text' self.w = One(self.txt) self.w1 = Two() print(self.txt) # not changed by One if __name__ == '__main__': app = QApplication(sys.argv) ex = Main() sys.exit(app.exec_())
这段代码里,Main类初始化了One类和Two类,我能把self.txt的值传给One类,但碰到两个问题:
- 在Two类的
printtxt方法里尝试打印One类的变量时触发属性错误:AttributeError: type object 'One' has no attribute 'mytext' AttributeError: type object 'One' has no attribute 'txt2' - 在One类里尝试修改Main类的
txt变量,但这个变量根本没被修改。
我想要实现的是:任意类创建的值能被所有已创建的类共享(类似局部范围的全局变量)。我觉得Bryan Oakley的Tkinter示例里的Controller概念接近解决方案,但需要更清晰的解释。
后来我重新研究了Controller模式,我的项目需要把4个独立程序合并并实现交互,还要尽量少改代码,Controller模式看起来是最简单的最优解。下面是基于这个模式的示例代码,或许能帮到其他开发者:
#!/usr/bin/python3 class SampleApp(): def __init__(self, *args, **kwargs): self.app_data = 'One' for F in (PageOne, PageTwo): frame = F(controller=self) class PageOne(): def __init__(self, controller): self.controller = controller value = self.controller.app_data print('Page1', value) class PageTwo(): def __init__(self, controller): self.controller = controller self.controller.app_data='Two' value = self.controller.app_data print('Page2',value) SampleApp()
内容的提问来源于stack exchange,提问作者John
相关产品推荐
相关产品推荐

