i*****f 发帖数: 578 | 1 # 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: affect the function interface
def func_with_static_var( arg1, arg2, static_var = [0] ):
static_var[0] += 1
print static_var[0]
# met | b****j 发帖数: 78 | 2 function itself is object, so:
def f():
if not hasattr(f, 'a'):
f.a = 0
f.a += 1
print f.a
【在 i*****f 的大作中提到】 : # 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()
| i*****f 发帖数: 578 | 3 oh, that's a nice one!
【在 b****j 的大作中提到】 : function itself is object, so: : def f(): : if not hasattr(f, 'a'): : f.a = 0 : f.a += 1 : print f.a
|
|