Python 有没有办法跟踪函数被调用的次数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21716940/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
is there a way to track the number of times a function is called?
提问by user3050527
So i'm trying to make a function that keeps track how many times a method is called. for example:
所以我试图制作一个函数来跟踪一个方法被调用的次数。例如:
a = [1,2,3,4]
a.pop()
i want to know how many times a.pop() was called so far so for this example, i would get 1. Is there a way to do this?
我想知道到目前为止 a.pop() 被调用了多少次,所以对于这个例子,我会得到 1。有没有办法做到这一点?
回答by aidnani8
A simple way to do this is to increment a global variable each time you call the function.
一个简单的方法是在每次调用函数时增加一个全局变量。
counter = 0
a = [1,2,3,4]
a.pop()
counter += 1
回答by mhlester
This doesn't work for builtin functions, but an interesting approach would be:
这不适用于内置函数,但一个有趣的方法是:
def myfunction():
myfunction.counter += 1
myfunction.counter = 0
You're giving the function an attribute, so every call that attribute is updated. No global variables needed.
你给函数一个属性,所以每次调用该属性都会更新。不需要全局变量。
Built-ins are read-only. They cannot be modified.
内置程序是只读的。它们不能被修改。
回答by castaway2000
counter = 0
def pop():
counter += 1
print counter
#other function code
a = [1,2,3,4]
a.pop()
this should solve your issue and you should be able to see whats being counted. + every time you call the function the counter is going to be increased and printed with every pass of the function.
这应该可以解决您的问题,您应该能够看到正在计算的内容。+ 每次调用该函数时,计数器都会随着函数的每次传递而增加和打印。
IF ITS BUILT IN:
如果它内置:
counter = 0
def newfunction():
a = [1,2,3,4]
a.pop()
counter += 1
print counter
the logic in this is that it will call your new function go into the function that is premade then step out of the built in function and then go on to mark the counter as increased. the output your counter.
其中的逻辑是,它将调用您的新函数进入预制函数,然后退出内置函数,然后继续将计数器标记为增加。输出你的计数器。
回答by FogleBird
You could use a decorator that tracks how many times the function is called. Since listis a built-in, you can't decorate or replace its popmethod so you'd have to use your own list class, for example.
您可以使用装饰器来跟踪函数被调用的次数。因为list是内置的,所以你不能装饰或替换它的pop方法,所以你必须使用你自己的列表类,例如。
def counted(f):
def wrapped(*args, **kwargs):
wrapped.calls += 1
return f(*args, **kwargs)
wrapped.calls = 0
return wrapped
class MyList(list):
@counted
def pop(self, *args, **kwargs):
return list.pop(self, *args, **kwargs)
x = MyList([1, 2, 3, 4, 5])
for i in range(3):
x.pop()
print x.pop.calls # prints 3
回答by jiminy_crist
For kicks, I wrote up an answer using a decorator:
为了好玩,我用装饰器写了一个答案:
class counter:
#wraps a function, to keep a running count of how many
#times it's been called
def __init__(self, func):
self.func = func
self.count = count
def __call__(self, *args, **kwargs):
self.count += 1
return self.func(*args, **kwargs)
To use it, simply decorate a function. You can then check how many times that function has been run by examining the "count" attribute. Doing it this way is nice because:
要使用它,只需装饰一个函数。然后,您可以通过检查“count”属性来检查该函数运行了多少次。这样做很好,因为:
1.) No global variables. The count is associated directly with the function.
1.) 没有全局变量。计数与函数直接相关。
2.) You can wrap builtin functions easily, by calling the class directly:
2.) 您可以通过直接调用类来轻松包装内置函数:
sum_wrapped = counter(sum)
sum_wrapped([1, 2 ,3, 4])
#outputs 10
print sum_wrapped.count
#outputs 1
Of course, this could be improved by using the Decoratorsmodule to keep the docstrings and other good things intact. Also, for an excellent overview of what decorators are, and how they work, check out this stackoverflow answer.
当然,这可以通过使用Decorators模块来改进,以保持文档字符串和其他好的东西完整无缺。此外,有关什么是装饰器及其工作方式的出色概述,请查看此 stackoverflow 答案。
回答by Matthew Trevor
One approach is to create a proxy of the instance for which you want to count attribute access:
一种方法是创建要计算属性访问的实例的代理:
from collections import Counter
class CountingProxy():
def __init__(self, instance):
self._instance = instance
self.count = Counter()
def __getattr__(self, key):
if hasattr(self._instance, key):
self.count[key] += 1
return getattr(self._instance, key)
>>> l = [1,2,3,4,5]
>>> cl = CountingProxy(l)
>>> cl.pop()
5
>>> cl.append(10)
>>> cl.index(3)
2
>>> cl.reverse()
>>> cl.reverse()
>>> cl.count
Counter({'reverse': 2, 'pop': 1, 'append': 1, 'index': 1})
回答by iiiir.com
i used the following little trick to track how many times the function was called
我使用以下小技巧来跟踪函数被调用的次数
def myfun(s,i=[0]):
print(s)
i[0]+=1 # mutable variable get evaluated ONCE
return i[0]
>>> myfun('aaa')
aaa
1
>>> myfun('bbb')
bbb
2
回答by ABHISHEK SRIVASTAVA
Just define a global variable and increment it inside function.
只需定义一个全局变量并在函数内部增加它。
a = 0
def some_function():
global a
a+=1
<..Your code.>
This will automatically be incremented as function is used and you can access it globally.
这将在使用函数时自动增加,您可以全局访问它。
回答by fralau
Here is a simple and elegant solution for a self counting function, without any decorators, global variables, etc:
这是一个简单而优雅的自计数函数解决方案,没有任何装饰器、全局变量等:
def hello():
hello.counter += 1
print(hello.counter)
hello.counter = 0
Each time you call hello(), it will print 1, 2, etc.
每次通话时间hello(),将打印1,2等等。
Let's not forget that, in Python, a function is a first-class citizen and it has rights. And one of them is to have attributes!
我们不要忘记,在 Python 中,函数是一等公民,它拥有权利。其中之一就是要有属性!
If you are willing to include your method call in a function, it can be easy:
如果您愿意在函数中包含您的方法调用,这很容易:
def pop_counted(a):
pop_counted.counter += 1
return a.pop()
pop_counted.counter = 0
Voilà!
瞧!
Comment
评论
This works because a Python function "knows" itself (this is a necessary feature, so that functions can call themselves recursively if desired).
这是有效的,因为 Python 函数“知道”自己(这是一个必要的特性,如果需要,函数可以递归调用自己)。
If you wish to keep some information about a function, it might be better to keep it where it belongs: in an attribute of the function.
如果您希望保留有关函数的一些信息,最好将其保留在它所属的位置:在函数的属性中。
The advantage of notusing a global variable is scope:
不使用全局变量的好处是作用域:
- no risk of name collisions in the global namespace
- the information you were keeping will vanish as soon as the function is taken off the stack, which is what you want -- no garbage left.
- 在全局命名空间中没有名称冲突的风险
- 一旦函数从堆栈中取出,您保留的信息就会消失,这正是您想要的——没有垃圾留下。
A bonus is that this approach will work in cases where a global variable is not really a good option, typically for nested functions where you can't declare a "global" in the outer function.
一个好处是,这种方法适用于全局变量不是真正好的选择的情况,通常用于无法在外部函数中声明“全局”的嵌套函数。
回答by Vincent Hunter
Just define a global statement in your function.
只需在您的函数中定义一个全局语句。
count = 1
def your_func():
global count
print(count)
count= count +1

