【发布时间】:2016-04-01 04:00:41
【问题描述】:
一个经常被问到的问题是 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
有什么理由我应该避免这种方法吗?无论如何,它到底是如何工作的?
【问题讨论】:
-
只是好奇,你为什么要这样做?这不就是为什么 python 有生成器吗?
-
我看到的大多数生成器示例都是用于简单的递增过程。此外,它们引入了另一个级别的缩进。我不是想
yeild一个数字,我只是希望能够返回该函数并存储我的最后一个值。就我而言,它是传入的一些东西的最大值。随之而来的是各种操作。 -
您链接到的页面上的装饰器解决方案有什么问题?无论如何,您链接到的页面上的所有解决方案看起来都很好。
-
我看不出任何客观邪恶的东西。
-
IDK。上课似乎有点矫枉过正。创建一个类,以便我实例化一个对象以执行其他语言中需要一行的事情?为什么它会在多线程环境中失败?