【问题标题】:Cannot change the value of global variable in Python [duplicate]无法在 Python 中更改全局变量的值 [重复]
【发布时间】:2018-08-06 05:33:45
【问题描述】:

我有一个函数,我想计算它被调用的次数(并以该计数器值作为名称保存图像)。我创建了一个名为 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)

【问题讨论】:

标签: python function global-variables


【解决方案1】:
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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-11-23
    • 2023-03-04
    • 1970-01-01
    • 1970-01-01
    • 2020-01-02
    • 2019-02-10
    • 2020-10-02
    相关资源
    最近更新 更多