问题描述
此外,在网络上可以找到许多不同的解决方案来创建静态变量.(虽然我还没有看到我喜欢的.)
Also, on the web one can find many different solutions to create static variables. (Though I haven't seen one that I like yet.)
为什么 Python 不支持方法中的静态变量?这被认为是非 Pythonic 还是与 Python 的语法有关?
Why doesn't Python support static variables in methods? Is this considered unpythonic or has it something to do with Python's syntax?
我专门询问了设计决策的为什么,但我没有提供任何代码示例,因为我想避免解释来模拟静态变量.
I asked specifically about the why of the design decision and I haven't provided any code example because I wanted to avoid explanation to simulate static variables.
推荐答案
这个省略背后的想法是静态变量只在两种情况下有用:当你真的应该使用一个类时,当你真的应该使用生成器时.
The idea behind this omission is that static variables are only useful in two situations: when you really should be using a class and when you really should be using a generator.
如果你想给一个函数附加状态信息,你需要的是一个类.也许是一个非常简单的类,但仍然是一个类:
If you want to attach stateful information to a function, what you need is a class. A trivially simple class, perhaps, but a class nonetheless:
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()
如果您希望函数的行为在每次调用时都改变,那么您需要一个生成器:
If you want your function's behavior to change each time it's called, what you need is a generator:
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
之外,你真的不需要任何东西——它可能看起来很笨拙,但对于小型的一次性脚本来说没问题:
Of course, static variables are useful for quick-and-dirty scripts where you don't want to deal with the hassle of big structures for little tasks. But there, you don't really need anything more than global
— it may seem a but kludgy, but that's okay for small, one-off scripts:
def foo():
global bar
do_stuff(bar)
foo()
foo()
这篇关于为什么 Python 没有静态变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!