使函数在第一次和后续调用之间表现不同

Har*_*ran 1 python

def download():
    upgrade = True
    if upgrade:
        # do a download using tftp
    else:
        # do a download via HTTP
Run Code Online (Sandbox Code Playgroud)

如您所见,我有一个设置为true的硬编码升级值.在此脚本中,它始终执行tftp下载.

如何在第一次迭代时更改脚本以执行tftp下载,在下一次迭代中调用函数下载时,它会进行http下载?

Ale*_*lex 6

为了完整性,这里是class解决方案:

class Download(object):
    def __init__(self):
        self.executed = False

    def __call__(self):
        print('http' if self.executed else 'tftp')
        self.executed = True

download = Download()

download()  # tftp
download()  # http
download()  # http
Run Code Online (Sandbox Code Playgroud)

这允许您以非hackish方式跨调用存储状态.