python decorator

发布时间:2024年01月15日

https://www.liujiangblog.com/course/python/39


import logging

# vesion1, add try...catch... for all method.
def outer(func):
    try:
        result = func()
        print("result is %s" % result)
        return result
    except Exception as ex:
        print("failed")
        raise Exception("failed due to %s ", str(ex))
@outer
def f1():
    print("f1")
    return None

# vesion2, decoratoer with specific parameter
def outerWithParam(func):
    def inner(name):
        try:
            result = func(name)
            print("result is %s" % result)
            return result
        except Exception as ex:
            print("failed")
            raise Exception("failed due to %s ", str(ex))

    return inner

@outerWithParam
def f2(name):
    # a = 1/0
    print("f2 %s" % name)
    return None

f2("kake")


# version 3, decorator with **kwargs.
def outerWithKwargs(func):
    def inner(**kwargs):
        try:
            result = func(**kwargs)
            print("result is %s" % result)
            return result
        except Exception as ex:
            print("failed")
            raise Exception("failed due to %s ", str(ex))

    return inner

@outerWithKwargs
def f3(name):
    print("f2 %s" % name)
    return None

f3(name='aa')

文章来源:https://blog.csdn.net/lingzhe7428/article/details/135599847
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。