有一个questions asking how to simulate static variables in python .
此外,在网络上可以找到许多不同的解决方案来创建静态变量。 (虽然我还没有看到我喜欢的。)
为什么 Python 不支持方法中的静态变量?这被认为是不符合 Python 的还是与 Python 的语法有关?
编辑:
我专门询问了设计决策的为什么,我没有提供任何代码示例,因为我想避免解释来模拟静态变量。
最佳答案
这个省略背后的想法是静态变量只在两种情况下有用:当你真的应该使用类时,以及当你真的应该使用生成器时。
如果你想将状态信息附加到一个函数,你需要一个类。也许是一个简单的类,但仍然是一个类:
def foo(bar):
static my_bar # doesn't work
if not my_bar:
my_bar = bar
do_stuff(my_bar)
foo(bar)
foo()
# -- becomes ->
class Foo(object):
def __init__(self, bar):
self.bar = bar
def __call__(self):
do_stuff(self.bar)
foo = Foo(bar)
foo()
foo()
如果您希望函数的行为在每次调用时都发生变化,那么您需要一个生成器:
def foo(bar):
static my_bar # doesn't work
if not my_bar:
my_bar = bar
my_bar = my_bar * 3 % 5
return my_bar
foo(bar)
foo()
# -- becomes ->
def foogen(bar):
my_bar = bar
while True:
my_bar = my_bar * 3 % 5
yield my_bar
foo = foogen(bar)
foo.next()
foo.next()
当然,静态变量对于你不想为小任务处理大结构的麻烦的快速而肮脏的脚本很有用。但是,除了 global
之外,你真的不需要任何东西——它可能看起来很笨拙,但对于小型的一次性脚本来说没关系:
def foo():
global bar
do_stuff(bar)
foo()
foo()
关于python - 为什么 Python 没有静态变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/592931/