zoukankan      html  css  js  c++  java
  • python 装饰器

    很久没有怎么用装饰器了,重新温习了一下装饰器的使用,直接上代码:

    #coding=utf-8



    def logging(level):
    def wrapper(func):
    def inner_wrapper(*args, **kwargs):
    print("[{level}]: enter function {func}()".format(
    level=level,
    func=func.__name__))
    return func(*args, **kwargs)
    return inner_wrapper
    return wrapper

    @logging(level='INFO')
    def say(something):
    print("say {}!".format(something))

    # 如果没有使用@语法,等同于
    # say = logging(level='INFO')(say)

    @logging(level='DEBUG')
    def do(something):
    print("do {}...".format(something))

    if __name__ == '__main__':
    say('hello')
    do("my work")

    运行结果如下:

    F:devpythonpython.exe F:/pyCharm/pratice/decorate_demo/demo_3.py
    [INFO]: enter function say()
    say hello!
    [DEBUG]: enter function do()
    do my work...

    Process finished with exit code 0

    class logging(object):
    def __init__(self, level='INFO'):
    self.level = level

    def __call__(self, func): # 接受函数
    def wrapper(*args, **kwargs):
    print("[{level}]: enter function {func}()".format(
    level=self.level,
    func=func.__name__))
    func(*args, **kwargs)
    return wrapper # 返回函数


    @logging(level='INFO')
    def say(something):
    print("say {}!".format(something))


    if __name__=="__main__":
    say("abccc")

    运行结果如下:

    F:devpythonpython.exe F:/pyCharm/pratice/decorate_demo/class_demo.py
    [INFO]: enter function say()
    say abccc!

    Process finished with exit code 0

  • 相关阅读:
    树的直径
    Codeforces 734E Anton and Tree(缩点+树的直径)
    Codeforces 948D Perfect Security(字典树)
    Codeforces 954D Fight Against Traffic(BFS 最短路)
    Codeforces 954C Matrix Walk (思维)
    Codeforces 950D A Leapfrog in the Array (思维)
    Codeforces 946D
    Invitation Cards POJ-1511 (spfa)
    spfa 单源最短路究极算法
    Currency Exchange POJ
  • 原文地址:https://www.cnblogs.com/linwenbin/p/10499853.html
Copyright © 2011-2022 走看看