python - Python 有类似 Perl 5.1 0's "state"variables 的东西吗?

标签 python perl

在 Perl 5.10 中,我可以说:

sub foo () {
  state $x = 1;
  say $x++;
}

foo();
foo();
foo();

...它会打印出:

1
2
3

Python有这样的东西吗?

最佳答案

类可能更适合这里(并且通常更适合任何涉及“状态”的事物):

class Stateful(object):

    def __init__(self):
        self.state_var = 0

    def __call__(self):
        self.state_var = self.state_var + 1
        print self.state_var

foo = Stateful()
foo()
foo()

关于python - Python 有类似 Perl 5.1 0's "state"variables 的东西吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/604622/

相关文章:

python - 无法通过 MySQLdb 在 Python 脚本中执行 INSERT 语句

python - Crontab 无法执行 python 脚本,错误为 : "[Errno 1] Operation not permitted"

perl - Mojolicious 响应缓存?

windows - Perl 包问题

python - 如何从全屏(!)VPython 窗口捕获屏幕?

python - 生成给定文件夹的文件名列表

java - Pycrypto AES GCM加密和Java解密

windows - 我可以从 Windows 命令行使用哪个 perl?

perl - 我可以从工具包模板文件中搜索结果集吗?

perl - 如何比较两个哈希值