gpt4 book ai didi

python - 无法更改Python中全局变量的值

转载 作者:行者123 更新时间:2023-12-01 09:10:27 24 4
gpt4 key购买 nike

我有一个函数,我想计算它被调用的次数(并以该计数器值作为名称保存图像)。我创建了一个名为 counter 的全局函数。但如果我这样做counter = counter+1 。它说Unresolved reference 。我错过了什么吗?

这是代码:

import numpy as np
import cv2
counter = 0
def saveImage(img):
counter = counter+1

imgs = str(counter) + '.jpg'
cv2.imwrite('images/'+imgs, img)

最佳答案

import numpy as np
import cv2
counter = 0
def saveImage(img):
global counter # to modify global variable, you need to explicitly declare so...
counter = counter+1

imgs = str(counter) + '.jpg'
cv2.imwrite('images/'+imgs, img)

关于python - 无法更改Python中全局变量的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51701087/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com