Skip to main content
 首页 » 编程设计

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

2025年05月04日14落叶无声

def download(): 
    upgrade = True 
    if upgrade: 
        # do a download using tftp 
    else: 
        # do a download via HTTP 

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

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

请您参考如下方法:

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

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 

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