Source From Here
Question
So i'm trying to make a function that keeps track how many times a method is called. for example:
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:
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()
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:
- 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
沒有留言:
張貼留言