Python 是否有类似 Perl 5.10 的“状态"之类的东西?变量? [英] Does Python have something like Perl 5.10's "state" variables?
本文介绍了Python 是否有类似 Perl 5.10 的“状态"之类的东西?变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在 Perl 5.10 中,我可以说:
In Perl 5.10, I can say:
sub foo () {
state $x = 1;
say $x++;
}
foo();
foo();
foo();
...它会打印出来:
1
2
3
Python 有这样的东西吗?
Does Python have something like this?
推荐答案
最接近的并行可能是将值附加到函数本身.
The closest parallel is probably to attach values to the function itself.
def foo():
foo.bar = foo.bar + 1
foo.bar = 0
foo()
foo()
foo()
print foo.bar # prints 3
这篇关于Python 是否有类似 Perl 5.10 的“状态"之类的东西?变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文