gpt4 book ai didi

python - 这个 Python "static variable"hack 可以使用吗?

转载 作者:太空狗 更新时间:2023-10-29 21:45:41 24 4
gpt4 key购买 nike

<分区>

一个经常被问到的问题是在 Python 中函数内部是否有一个等价于静态变量的东西。答案有很多,比如创建包装类、使用嵌套函数、装饰器等。

我找到的最优雅的解决方案之一是 this ,我稍作修改:

def foo():
# see if foo.counter already exists
try: test = foo.counter
# if not, initialize it to whatever
except AttributeError: foo.counter = 0

# do stuff with foo.counter
.....
.....

例子:

static.py

def foo(x):
# see if foo.counter already exists
try: test = foo.counter
# if not, initialize it to whatever
except AttributeError: foo.counter = 0

foo.counter += x

print(foo.counter)

for i in range(10):
foo(i)

输出

$ python static.py
0
1
3
6
10
15
21
28
36
45

有什么理由我应该避免这种方法吗?它到底是如何工作的?

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