How can I, say, multiply args by any number? args * 2 gives an error

 def main(args): def wrapping(): return args return wrapping() @main def factorial(n): if n == 0: return 1 else: return n * factorial(n - 1) print(factorial(5)) 

    2 answers 2

    Example:

     In [3]: def decorator(func): ...: def wrapper(n): ...: return func(n * 2) ...: return wrapper ...: In [4]: @decorator ...: def foo(n): ...: return n ...: In [5]: foo(10) Out[5]: 20 

    You can also pass the parameter to the decorator:

     In [7]: def decorator(x): ...: def wrapper(func): ...: def inner(n): ...: return func(n * x) ...: return inner ...: return wrapper ...: In [8]: @decorator(5) ...: def foo(n): ...: return n ...: In [9]: foo(10) Out[9]: 50 

      The decorator takes the original function as an argument, and usually returns a function that takes the same arguments as the original, and returns the result of calling it with these arguments.

      For example, to double the argument of the function being decorated, you can do this

       def main(f): # f - это декорируемая функция def wrapping(n): # эта функция заместит оригинальную, должна принимать тот же аргумент return f(2 * n) # и вызывать оригинальную функцию с удвоенным аргументом return wrapping # возвращаем функцию @main def square(x): return x * x print(square(5)) # 100 

      Only with factorial it does not work, because already decorated function will be recursively called inside factorial, so the argument will grow endlessly and cause stack overflow, but you can make a function that doubles the result , not the argument, then the calculation ends, though and also a bit with an unexpected result

       def main2(f): def wrapping(n): return 2 * f(n) return wrapping @main2 def factorial(n): if n == 0: return 1 else: return n * factorial(n - 1) print(factorial(5)) # 7680 

      2 * 5 * ( 2 * 4 * ( 2 * 3 * ( 2 * 2 * ( 2 * 1 * ( 2 * 1))))) = 7680

      • Thanks, one conclusion, the task will not be solved with this method of factorial, redid the code and just multiplied by the number, everything turned out, thank you. - Qualcomm Atheros