2021年7月3日 星期六

[ Python 常見問題 ] Is there a way to track the number of times a function is called?

 Source From Here

Question
So i'm trying to make a function that keeps track how many times a method is called. for example:
  1. a = [1,2,3,4]  
  2. 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?

HowTo
You could use a decorator that tracks how many times the function is called. Since list is a built-in, you can't decorate or replace its pop method so you'd have to use your own list class, for example:
  1. def counted(f):  
  2.     def wrapped(*args, **kwargs):  
  3.         wrapped.calls += 1  
  4.         return f(*args, **kwargs)  
  5.     wrapped.calls = 0  
  6.     return wrapped  
  7.   
  8. class MyList(list):  
  9.     @counted  
  10.     def pop(self, *args, **kwargs):  
  11.         return list.pop(self, *args, **kwargs)  
  12.   
  13. x = MyList([12345])  
  14. for i in range(3):  
  15.     x.pop()  
  16.   
  17. print x.pop.calls # prints 3  


沒有留言:

張貼留言

[Git 常見問題] error: The following untracked working tree files would be overwritten by merge

  Source From  Here 方案1: // x -----删除忽略文件已经对 git 来说不识别的文件 // d -----删除未被添加到 git 的路径中的文件 // f -----强制运行 #   git clean -d -fx 方案2: 今天在服务器上  gi...