在class_instance.py模块中,我创建了print_time方法。并实例化对象app
rom tkinter import Button, Tk, HORIZONTAL
from tkinter.ttk import Progressbar
import time
class MonApp(Tk):
def __init__(self):
super().__init__()
bt1 = Button(self, text='Traitement', command=self.traitement)
bt1.grid()
self.progress = Progressbar(self, orient=HORIZONTAL, length=100, mode='indeterminate')
self.progress.grid()
self.progress.grid_forget()
def traitement(self):
self.progress.grid()
self.a = self.progress.start()
time.sleep(15)
## Just like you have many, many code lines...
self.b = self.progress.stop()
def print_time(self):
print("下载开始时间{}" % self.a)
print("下载结束时间{}" % self.b)
if __name__ == '__main__':
app = MonApp()
app.mainloop()
在另外fun.py模块中,我想用类的print_time方法
import class_instance
def c():
print("调入类方法的结果")
class_instance.app.print()
if __name__ == '__main__':
c()
但运行结果却告知module 'class_instance' has no attribute 'app'模块.
AttributeError: module 'class_instance' has no attribute 'app'
1.我又不能在第二个模块中重新实化一个新对象,那样就想是重新启动了一个GUI;
2.我考虑过@staticmethod和@classmethod,对print_time函数静态方法,没有self,这样就不能读取到self.a,self.b。而动态方法传入cls,也是无法读取到self.a, self.b参数的。
想要fun.py中,如何不重新实例化一个新对象的情况下,访问类方法print_time
类方法必须依赖于类的实例。
而且当你使用fun.py时,你并没有创建一个实例。app是在被调用模块py文件作为主运行文件时创建的,因为你加了当前运行文件条件判断。因此你完全可以导入那个类,并进行实例化,这样并没有产生两个实例。