如何更改每个函数中的全局变量而不影响 Python 中的函数?

how can I change the global variable in each function without the functions affecting each other in Python?

我的全局变量 count=0 正在以下函数(方法)中更改:

def Counter(counter,boolean=False)->int:
    if boolean:
        counter+=1
    else:
        counter=0

    return counter

等函数使用Counter函数:

def func1():
    global count
    count=Counter(count,True)
    print("func1:",count)

def func2():
    global count
    count=Counter(count,True)
    print("func2:",count)

当运行这些功能再次像for循环

for _ in range(3):
    func1()
    func2()

输出是:

func1:1
func2:2
func1:3
func2:4
func1:5
func2:6

但输出必须是这样的:

func1:1
func2:1
func1:2
func2:2
func1:3
func2:3

我研究了不同的方法,但找不到答案。我该怎么做?

为什么之前的代码不起作用?

global 关键字使两个函数都可以访问计数器变量。
使用 global 变量是 bad-practice,不要那样做。

如何实现你所要求的?

下面的词为每个函数分配一个计数器,在每次调用时修改它。


def func1():
    func1.count+=1
    print("func1:", func1.count)

def func2():
    func2.count += 1
    print("func1:", func2.count)

func1.count=0
func2.count=0

for _ in range(3):
    func1()
    func2()

更多关于

你问的是如何在 python 函数中使用 static-variable。
术语 'function static variable' 指的是函数可访问和拥有的变量。
Python 不以 straight-forward 方式支持静态变量,例如 C# 或 Java 等语言,但在 thread, those are more complex and require the usage of decorators 中还有其他漂亮的解决方案 - 所以我没有提他们。