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

标签 python

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 方式跨调用存储状态。

关于python - 使函数在第一次调用和后续调用之间表现不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48673304/

相关文章:

python matplotlib plotfile显式使用 float

python - pandas read sql query 和 read sql table 的区别

python - 如何使用两个或多个列表进行查询集过滤?

python - django admin - 选择反向外键关系(不是创建,我想添加可用)

python - 如何在 Python 中手动中止函数同时仍返回结果

Python 使用 minidom 编辑 xml

python - Python 中的协同过滤

Python Django 编码错误,非 ASCII 字符 '\xe5'

python - 如何使用 python 将确认从后台函数返回到 pubsub

python - 洗牌参数