python - Cannot change the value of global variable in Python
问题描述
I have a function that I want to count how many times it is called (and save a image with that counter value as its name). I made a global function called counter
. But if I do counter = counter+1
. It says Unresolved reference
. Am I missing something ?
Here is the code :
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 - 能够跟随非常急转弯和路口的线跟随机器人(带摄像头)的算法
- c++ - 如何正确使用 string::erase
- vue.js - 为 Veutify Input 控件指定默认主题
- ios - 使用 IBMCloudAppID 授权委托时,委托不符合协议
- algorithm - 曼德布罗集边界的保守渲染
- google-cloud-firestore - 如何触发 onwrite 将数据复制到不同 Firestore 中的集合
- c# - 在时区获取当前时间没有考虑夏令时(我认为)
- actionscript-3 - FlashDevelop 将整个类路径放在新实例声明中
- c++ - How do I keep a running total of an input variable inside of a switch?
- shell - How do I get grep working in a function while assigned to a new variable?