python - 为什么 Python 没有静态变量?

标签 python

有一个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/

相关文章:

python - 使用 Python pandas 格式化数据框

python - 使用 Python Twisted 进行 UDP 流量控制

python时间序列将各个工作日绘制为线

python - Django 1.8.5。如何使用 get_language() 在我的应用程序的 admin.py 中的 Model.Admin 中定义用户语言?

python - 字符串和 int 格式中 float 的区别。为什么?

python - 图像 Python 的滚动统计

python - 如何在 python 中导入已完成进程的环境变量?

python - 使用最大日期字段和收入字段按类别进行新列计算

java - 解析 Java 程序的 Python 配置文件

python Pandas : create variable for unique combinations of 2 categorical variables?