为什么Python没有静态变量?

2024-10-07 22:16:25 发布

您现在位置:Python中文网/ 问答频道 /正文

有一个questions asking how to simulate static variables in python

另外,在web上可以找到许多不同的解决方案来创建静态变量。(虽然我还没看到我喜欢的。)

为什么Python不支持方法中的静态变量?这被认为是不通俗的还是与Python的语法有关?

编辑:

我特别询问了设计决策的为什么,我没有提供任何代码示例,因为我想避免对模拟静态变量的解释。


Tags: to方法inweb编辑静态语法static
3条回答

类的另一种选择是函数属性:

def foo(arg):
    if not hasattr(foo, 'cache'):
        foo.cache = get_data_dict()
    return foo.cache[arg]

虽然一个类可能更干净,但在我看来,这种技术可能更有用,而且比全局技术更好。

在Python3中,我将使用一个闭包:

def makefoo():
    x = 0
    def foo():
        nonlocal x
        x += 1
        return x
    return foo

foo = makefoo()

print(foo())
print(foo())

这种省略背后的想法是静态变量只在两种情况下有用:当您真的应该使用类时,以及当您真的应该使用生成器时。

如果要将有状态信息附加到函数,则需要一个类。可能是一个简单的类,但仍然是一个类:

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()

相关问题 更多 >