【发布时间】:2016-05-26 02:05:21
【问题描述】:
考虑以下小型 Python GUI 程序,用户可以在其中反复单击按钮以在窗口 1 和窗口 2 之间循环:
import tkinter
class Window1:
def __init__(self, parent):
# Initialize a new GUI window
self.parent = parent
self.window = tkinter.Toplevel(self.parent)
self.window.title('Window 1')
# Make a button to launch Window 2
launch_window_2_button = tkinter.Button(self.window, text='Launch Window 2')
launch_window_2_button.config(command=self.launch_window_2)
launch_window_2_button.pack()
def launch_window_2(self):
self.window.destroy()
Window2(self.parent)
class Window2:
def __init__(self, parent):
# Initialize a new GUI window
self.parent = parent
self.window = tkinter.Toplevel(self.parent)
self.window.title('Window 2')
# Make a button to launch Window 1
launch_window_1_button = tkinter.Button(self.window, text='Launch Window 1')
launch_window_1_button.config(command=self.launch_window_1)
launch_window_1_button.pack()
def launch_window_1(self):
self.window.destroy()
Window1(self.parent)
if __name__ == "__main__":
# Initialize and hide the root GUI
# (each class will spawn a new window that is a child of the root GUI)
root = tkinter.Tk()
root.withdraw()
Window1(root) # Start by spawning Window 1
root.mainloop()
问题 1:由于每个新类都是从另一个类中实例化的,这是否是内存泄漏?
问题 2:这是编写此应用程序的最正确和 Pythonic 的方式吗?
问题 3: 假设问题 1 的答案是否定的,如果我将 Window1(self.parent) 更改为 self.something = Window1(self.parent) 会怎样。既然有了引用,现在是不是内存泄漏了?
【问题讨论】:
-
内存泄漏是指您在不再使用内存时不释放内存。例如,如果您有一个程序从文件中读取行,并且您为每一行分配新内存,但在读取下一行之前从未释放一行的内存,这就是内存泄漏。无法释放该内存,因为您不再拥有对它的引用,因此您的程序使用的内存量将不断增长。 Python 为您管理内存,在这种情况下,内存将自动释放。对象的实例化方式或位置与它无关。
标签: python object memory-leaks