def counter(func): def wrapper(*args, **kwargs): wrapper.count += 1 # Call the function being decorated and return the result return wrapper.count wrapper.count = 0 # Return the new decorated function return wrapper # Decorate foo() with the counter() decorator @counter def foo(): print('calling foo()') foo() foo() print('foo() was called {} times.'.format(foo.count))
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter