我创建了一个应用程序,它只有 1 个包含所有功能的大类。代码运行正常。
代码可以分为几个部分,例如:GUI、处理任务的纯块代码。
我想将原始类分成 2 个类,1 个是应用程序的 GUI,另一个是处理任务的块代码。
问题是,当我这样做时,2 个类使用另一个的实例变量。我该如何解决这个问题,请帮忙,谢谢。
原始类示例:
Class App:
def __init__(self):
self.var1 = 'first variable'
self.var3 = 'third variable'
def method1(self):
self.var2 = 'second variable'
print(self.var3)
def method2(self):
print(self.var2)
self.method1()
以下是 2 个新类的示例(我只是将它们拆分并没有修改任何内容):
Class GUI:
def __init__(self):
self.var1 = 'first variable'
def method1(self):
self.var2 = 'second variable'
print(self.var3) # <-- var3 is belonged to class Core
Class Core:
def __init__(self):
self.var3 = 'third variable'
def method2(self):
print(self.var2) # <-- var 2 is belonged to class GUI
self.method1() # <-- method1 belonged to class GUI too
答案 0 :(得分:2)
我认为这是解决方案:
class GUI:
var2 = None
def __init__(self):
self.var1 = 'first variable'
@staticmethod
def method1():
GUI.var2 = 'second variable'
print(Core.var3) # <-- var3 is belonged to class Core
class Core:
var3 = None
def __init__(self):
Core.var3 = 'third variable'
@staticmethod
def method2():
print(GUI.var2) # <-- var 2 is belonged to class GUI
GUI.method1() # <-- method1 belonged to class GUI too
你应该让你的变量和方法static
。您可以在此处阅读有关 python
中的静态方法和变量的更多信息:Are static class variables possible in Python?