python装饰器示例

python装饰器示例

理解python装饰器需要先了解闭包和作用域,网上有很多相关文章,大家自行了解下,这里给出装饰器的常用使用场景示例,方便大家理解。

1. 不带参数的装饰器

def checkpwd(func):
    def startcheck():
        print("校验密码中。。。")
        return func()
    return startcheck

@checkpwd
def withdraw():
    print("取钱中。。。")

withdraw()

2. 带参数的装饰器

def checkpwd(type):
    if "type" == "USD":
        print("您正在取得是美元")
    else:
        print("您正在取得是人民币")
    def startcheck(func):
        print("校验密码中。。。")
        return func
    return startcheck

@checkpwd("USD")
def withdraw():
    print("取钱中。。。")

withdraw()

3. 被装饰函数带参数

def checkpwd(func):
    def startcheck(num):
        print("校验密码中。。。")
        num = num + 5
        return func(num)
    return start-check

@checkpwd
def withdraw(num):
    print("取钱中。。。金额为:", num)

withdraw(5)

4. 被装饰函数及装饰器都带参数

def checkpwd(type):
    if type == "USD":
        print("您在取美元")
    else:
        print("您在取人民币")
    def startcheck(func):
        print("校验密码中")
        def startcheck1(*args, **kwargs):
            func(int(*args)+5, **kwargs)
        return startcheck1
    return startcheck

@checkpwd("USD")
def withdraw(num):
    print("取钱中。。。金额为:", num)

withdraw(5)
hcwei