简体   繁体   中英

How to update a global variable across multiple functions in Python

I have the following code:

counter = 0
def function_1():
  func_2(counter)

def func_2(counter):
  func_3(counter)

def func_3(counter):
   counter += 1

My goal is to keep track of counter incrementation in func_3() in all other functions.

I tried to make counter global

counter = 0
def function_1():
  global counter
  func_2(counter)

def func_2(counter):
  func_3(counter)

def func_3(counter):
   counter += 1

but it does not work, the counter incrementation is just local to func_3()

Any hints?

I tried to find an easy to understand explanation for you, but they all seemed to complicated.

The reason that you are seeing counter as a local variable inside your functions is because you are defining it in the function definition: def func_2(counter): .

To use the global counter inside a function you need to do it like this:

counter = 0

def function_1():
  func_2()

def func_2():
  func_3()

def func_3():
   global counter
   counter += 1

You can use globals().update(locals()) , example:

counter = 0
def function_1():
  func_2()

def func_2():
  func_3()

def func_3():
  counter += 1
  globals().update(locals())

or use global method

counter = 0
def function_1():
  func_2()

def func_2():
  func_3()

def func_3():
  global counter
  counter += 1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM