用easyui做的网站南宁seo多少钱报价
这种省略背后的想法是静态变量只在两种情况下有用:当您真的应该使用类时,以及当您真的应该使用生成器时。
如果要将有状态信息附加到函数,则需要一个类。可能是一个简单的类,但仍然是一个类: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()