函数间共享列表

Sharing list between functions

我最近问了另一个问题,询问如何将列表从一个函数传递到另一个函数,@Modred 友善地回答了这个问题。基本上我现在得到的是:

def run_command():
    machines_off = []
        # Some stuff .....
        machines_off.append(machineName)
        # Some stuff ....
    wol_machines(machines_off)

def wol_machines(machines_off):
    # Some stuff ....

(我已经清除了这个例子的所有非必要代码,因为它有 300 多行)。

现在,每个函数都是通过点击一个 tkinter 按钮来调用的; run_command 始终运行,有时会将项目添加到列表 'machines_off'。如果单击第二个功能按钮,我只希望它动作 machines_off。在单击 run_command 按钮后的那一刻,它运行了整个脚本,包括我不希望的第二个函数。我假设当我将列表转发到第二个函数(第 5 行)时,它绕过了单击第二个函数按钮的需要。

我需要做什么才能change/add 允许第一个函数的列表对第二个函数可用,但在需要时不执行它??

非常感谢, 克里斯。

我猜您的代码类似于:

from Tkinter import Tk, Button

def run_command():
    machines_off = []
    # Some stuff .....
    machineName = "foo"
    machines_off.append(machineName)
    # Some stuff ....
    wol_machines(machines_off)

def wol_machines(machines_off):
    print "wol_machines was called"
    print "contents of machines_off: ", machines_off
    # Some stuff ....

root = Tk()
a = Button(text="do the first thing", command=run_command)
b = Button(text="do the second thing", command=wol_machines)
a.pack()
b.pack()

root.mainloop()

如果您希望函数彼此独立执行,则不应从 run_command 中调用 wol_machines。您必须为这两个函数找到一些其他方式来查看列表。一种方法是使用全局值。

from Tkinter import Tk, Button

machines_off = []

def run_command():
    #reset machines_off to the empty list.
    #delete these next two lines if you want to retain old values.
    global machines_off
    machines_off = []
    # Some stuff .....
    machineName = "foo"
    machines_off.append(machineName)
    # Some stuff ....

def wol_machines():
    print "wol_machines was called"
    print "contents of machines_off: ", machines_off
    # Some stuff ....

root = Tk()
a = Button(text="do the first thing", command=run_command)
b = Button(text="do the second thing", command=wol_machines)
a.pack()
b.pack()

root.mainloop()

这是可以为您提供所需行为的对原始代码的最简单更改,但全局值通常被认为是不良设计的标志。一种更面向对象的方法可以将全局本地化为 class 属性。

from Tkinter import Tk, Button

class App(Tk):
    def __init__(self):
        Tk.__init__(self)
        self.machines_off = []
        a = Button(self, text="do the first thing", command=self.run_command)
        b = Button(self, text="do the second thing", command=self.wol_machines)
        a.pack()
        b.pack()
    def run_command(self):
        #reset machines_off to the empty list.
        #delete this next line if you want to retain old values.
        self.machines_off = []
        # Some stuff .....
        machineName = "foo"
        self.machines_off.append(machineName)
        # Some stuff ....

    def wol_machines(self):
        print "wol_machines was called"
        print "contents of machines_off: ", self.machines_off
        # Some stuff ....

root = App()
root.mainloop()