可能重复:
Static class variables in Python
What is the Python equivalent of static variables inside a function?Python中的函数的静态成员?
我如何可以使用Python中的静态字段?
例如,我想计算函数被调用了多少次 - 我该如何做到这一点?
可能重复:
Static class variables in Python
What is the Python equivalent of static variables inside a function?Python中的函数的静态成员?
我如何可以使用Python中的静态字段?
例如,我想计算函数被调用了多少次 - 我该如何做到这一点?
如果要算多少次的方法被调用,无论哪个实例调用它,你可以使用一个类的成员如下:
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
当你定义calls
这样:
class Foo(object):
calls=0
Python将键值对('calls',0)放在Foo.__dict__
中。可以是访问Foo.calls
。 Foo
的实例(如foo=Foo()
)也可以使用foo.calls
访问它。
至分配新值为Foo.calls
您必须使用Foo.calls = ...
。 实例无法使用foo.calls = ...
,因为这会导致Python在保留实例成员的foo.__dict__
中放置新的不同的键值对。
下面是一些例子计算同一类的所有对象的调用次数:
class Swallow():
i = 0 # will be used for counting calls of fly()
def fly(self):
Swallow.i += 1
这是证明:
>>> a = Swallow()
>>> b = Swallow()
>>> a.fly()
>>> a.i
1
>>> Swallow.i
1
>>> b.fly()
>>> b.i
2
>>> Swallow.i
2
,因此您可以通过给对象阅读姓名或班级名称。
这是一个将计数添加到函数的装饰器。
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
用法:
>>> @count_calls
... def foo():
... pass
...
>>> foo.count
0
>>> foo()
>>> foo.count
1
这里有一个简单的方法来做到这一点:
def func():
if not hasattr(func, 'counter'):
func.counter = 0
func.counter += 1
counter = 0 # Not the same as `func.counter`
print(func.counter)
或者,如果你如果在每次调用执行不喜欢,你可以这样做:
def func():
func.counter += 1
print(func.counter)
func.counter = 0
同意:重复 – gecco
@PaulManta:我d isagree。您的链接与类静态字段(如OP所述)无关,而是与您在所给问题中使用的链接所指的OP中“在功能级别上的静态成员,而不是类级别_”相关。 – Tadeck
@Tadeck'class'这个词甚至没有出现在问题中......但是“一个函数**的静态成员**”这个短语的确如此。 –