初始化循环中的变量是否使用全局变量?

2024-09-27 23:21:51 发布

您现在位置:Python中文网/ 问答频道 /正文

我写了一个函数,可以制作一个屏幕截图,并检查它是否与旧的不同。下面是示例代码。但是,我想知道pythons设置oldimage和image变量的最佳实践。尤其是在main()第一次启动之前需要设置oldimage。我使用全局变量吗?你知道吗

def main():
    image=screenGrab()
    if equal(image,oldimage):
        pass
    else:
        dosomething()
        oldimage=image

while True:
    main()

Tags: 函数代码image示例if屏幕maindef
1条回答
网友
1楼 · 发布于 2024-09-27 23:21:51

使用全局变量几乎从来都不是正确的解决方案。它通常会导致比解决方案更多的问题。从@MartijnPieters继续,我将按照以下方式组织您的代码:

def main():
    oldimage = loadLastImage()

    while True:
        image=screenGrab()
        if not equal(image,oldimage):
            dosomething()
            saveLastImage(image) # this is the opposite of loadLastImage()
            oldimage=image

# this is the more accepted way of running main 
# because it still allows your code to be loaded as module
if __name__ == "__main__":
    main()

相关问题 更多 >

    热门问题