Static member of a function in Python ?
本问题已经有最佳答案,请猛点这里访问。
Possible Duplicate:
Static class variables in Python
What is the Python equivalent of static variables inside a function?
如何在Python中使用静态字段?
例如,我想计算函数被调用了多少次-我该怎么做?
如果您想计算一个方法被调用了多少次,不管哪个实例调用了它,您都可以使用这样的类成员:
1 2 3 4 5 6 7 8 9 10 11 12 | class Foo(object): calls=0 # <--- call is a class member def baz(self): Foo.calls+=1 foo=Foo() bar=Foo() for i in range(100): foo.baz() bar.baz() print('Foo.baz was called {n} times'.format(n=foo.calls)) # Foo.baz was called 200 times |
当您这样定义
1 2 | class Foo(object): calls=0 |
python将键值对("calls",0)放在
可通过
要为
这是一个向函数添加计数的装饰器。
1 2 3 4 5 6 7 8 9 | import functools def count_calls(func): @functools.wraps(func) def decor(*args, **kwargs): decor.count += 1 return func(*args, **kwargs) decor.count = 0 return decor |
用途:
1 2 3 4 5 6 7 8 9 | >>> @count_calls ... def foo(): ... pass ... >>> foo.count 0 >>> foo() >>> foo.count 1 |
下面是一些计算同一类所有对象调用次数的示例:
1 2 3 4 | class Swallow(): i = 0 # will be used for counting calls of fly() def fly(self): Swallow.i += 1 |
这就是证据:
1 2 3 4 5 6 7 8 9 10 11 12 | >>> a = Swallow() >>> b = Swallow() >>> a.fly() >>> a.i 1 >>> Swallow.i 1 >>> b.fly() >>> b.i 2 >>> Swallow.i 2 |
因此,您可以通过提供对象名或类名来读取它。
这是一种简单的方法:
1 2 3 4 5 6 | def func(): if not hasattr(func, 'counter'): func.counter = 0 func.counter += 1 counter = 0 # Not the same as `func.counter` print(func.counter) |
或者,如果您不喜欢在每次调用时执行if,则可以执行以下操作:
1 2 3 4 | def func(): func.counter += 1 print(func.counter) func.counter = 0 |