0

I am having difficulties understanding the concept of parameterized decorator and how it works. Could someone please explain how it works and what would the decorator base look like in the example below:

@base(10)
def sum(x,y):
    return x+y

print(sum(1,2))
Oleole
  • 381
  • 4
  • 21
  • 1
    Possible duplicate of [python decorators with parameters](http://stackoverflow.com/questions/5929107/python-decorators-with-parameters) – miradulo Nov 14 '16 at 16:25
  • Decorator is a function that returns a function. Parameterized decorator is a function that returns decorator. – Alex Nov 14 '16 at 16:29

1 Answers1

0

Code speaks more than a thousand words:

def int2base(x, base):
    """ Converts int to string with given base representation.
        Credit to @Alex Martelli on http://stackoverflow.com/questions/2267362/convert-integer-to-a-string-in-a-given-numeric-base-in-python"""

    if x < 0: sign = -1
    elif x == 0: return digs[0]
    else: sign = 1
    x *= sign
    digits = []
    while x:
        digits.append(digs[x % base])
        x //= base
    if sign < 0:
        digits.append('-')
    digits.reverse()
    return ''.join(digits)


def base(num):
    def decorator(func):
        def wrapper(*args):
            return int2base(func(*args), num)
        return wrapper
    return decorator


def my_sum(num1, num2):
    return num1 + num2

# using decorator syntax
@base(2)
def my_sum2(num1, num2):
    return num1 + num2

print(my_sum(1,2))
print(my_sum2(1,2))

# decorating manually
decorator = base(2) # base acts kinda like factory method
my_sum2_manual = decorator(my_sum)
print(my_sum2_manual(1,2))
thorhunter
  • 483
  • 7
  • 9