i*****f 发帖数: 578 | 1 【 以下文字转载自 Python 俱乐部 】
发信人: icewolf (好好活), 信区: Python
标 题: Static variables in function
发信站: BBS 未名空间站 (Fri Feb 12 16:50:57 2010, 美东)
# method 1: a callable instance
# pros: good encapsulation
# cons: too verbal
class _func_with_static_var:
def __init__(self):
self.static_var = 0
def __call__(self, *args):
self.static_var += 1
print self.static_var
func_with_static_var = _func_with_static_var()
# method 2: pass as a list with default value
# pros: less verbal
# cons: a |
r****t 发帖数: 10904 | 2 method 1,3 are the standard, not limited to be within function.
method 2 is a nice trick, but 初学者一定会搞错, limited in a function。 |
X****r 发帖数: 3557 | 3 # method 4: save in the function object itself
# pros: easy and simple
# cons: possible attribute name collision
def func_with_static_var():
func_with_static_var.static_var = getattr(func_with_static_var,
'static_var', 0) + 1
print func_with_static_var.static_var
【在 i*****f 的大作中提到】 : 【 以下文字转载自 Python 俱乐部 】 : 发信人: icewolf (好好活), 信区: Python : 标 题: Static variables in function : 发信站: BBS 未名空间站 (Fri Feb 12 16:50:57 2010, 美东) : # method 1: a callable instance : # pros: good encapsulation : # cons: too verbal : class _func_with_static_var: : def __init__(self): : self.static_var = 0
|
X****r 发帖数: 3557 | 4 # method 5: save in a closure
# pros: really good encapsulation
# cons: verbose
def _func_with_static_var():
static_var = [0]
def actual_func():
static_var[0] += 1
print static_var[0]
return actual_func
func_with_static_var = _func_with_static_var()
【在 X****r 的大作中提到】 : # method 4: save in the function object itself : # pros: easy and simple : # cons: possible attribute name collision : def func_with_static_var(): : func_with_static_var.static_var = getattr(func_with_static_var, : 'static_var', 0) + 1 : print func_with_static_var.static_var
|
r****t 发帖数: 10904 | 5 帅锅你不是反对这么搞么?
【在 X****r 的大作中提到】 : # method 4: save in the function object itself : # pros: easy and simple : # cons: possible attribute name collision : def func_with_static_var(): : func_with_static_var.static_var = getattr(func_with_static_var, : 'static_var', 0) + 1 : print func_with_static_var.static_var
|
X****r 发帖数: 3557 | 6 我只是提出一种方法。我自己的程序多半还是会按#1或者#3来写。
话说回来我不记得我有在什么地方说过反对过这么搞吧?虽然我的确不推荐这个。
【在 r****t 的大作中提到】 : 帅锅你不是反对这么搞么?
|
r****t 发帖数: 10904 | 7 很早以前听你说过的,俺牢记于心。。。
【在 X****r 的大作中提到】 : 我只是提出一种方法。我自己的程序多半还是会按#1或者#3来写。 : 话说回来我不记得我有在什么地方说过反对过这么搞吧?虽然我的确不推荐这个。
|