Python function decorator error -


i tried use function decorators, in example dooesn't work me, can give me solution ?

def multiply_by_three(f):     def decorator():         return f() * 3 return decorator  @multiply_by_three def add(a, b):       return + b  print(add(1,2)) # returns (1 + 2) * 3 = 9 

interpreter prints error: "typeerror: decorator() takes 0 positional arguments 2 given"

when use decorator, function return decorator replaces old function. in other words, decorator function in multiply_by_three replaces add function.

this means each functions signature's should match, including arguments. however, in code add takes 2 arguments while decorator takes none. need let decorator receive 2 arguments well. can using *args , **kwargs:

def multiply_by_three(f):     def decorator(*args, **kwargs):         return f(*args, **kwargs) * 3     return decorator 

if decorate function , run it, can see works:

@multiply_by_three def add(a, b):       return + b  print(add(1,2)) # 9 

Comments

Popular posts from this blog

ubuntu - PHP script to find files of certain extensions in a directory, returns populated array when run in browser, but empty array when run from terminal -

php - How can i create a user dashboard -

javascript - How to detect toggling of the fullscreen-toolbar in jQuery Mobile? -