在python中使用参数化装饰器

时间:2016-11-14 16:24:45

标签: python decorator python-decorators

我很难理解参数化装饰器的概念及其工作原理。有人可以解释它是如何工作的以及装饰器基础在下面的例子中会是什么样子:

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

print(sum(1,2))

1 个答案:

答案 0 :(得分:0)

代码说了千言万语:

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))