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

    def works_for_all(func):
        def inner(*args, **kwargs):
            print("I can decorate any function")
            return func(*args, **kwargs)
        return inner

    例子一

    def make_pretty(func):
        def inner():
            print("I got decorated")
            func()
        return inner
    
    def ordinary():
        print("I am ordinary")

    执行

    >>> ordinary()
    I am ordinary
    
    >>> # let's decorate this ordinary function
    >>> pretty = make_pretty(ordinary)
    >>> pretty()
    I got decorated
    I am ordinary

    例子二

    def make_pretty(func):
        def inner():
            print("I got decorated")
            func()
        return inner
    
    @make_pretty
    def ordinary():
        print("I am ordinary")
    
    ordinary()

    输出

    I got decorated
    I am ordinary

    例子三

    def star(func):
        def inner(*args, **kwargs):
            print("*" * 30)
            func(*args, **kwargs)
            print("*" * 30)
        return inner
    
    def percent(func):
        def inner(*args, **kwargs):
            print("%" * 30)
            func(*args, **kwargs)
            print("%" * 30)
        return inner
    
    @star
    @percent
    def printer(msg):
        print(msg)
    printer("Hello")

    输出

    ******************************
    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    Hello
    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    ******************************

    上面的

    @star
    @percent
    def printer(msg):
        print(msg)

    相当于

    def printer(msg):
        print(msg)
    printer = star(percent(printer))

  • 相关阅读:
    pionter指针小结
    C++笔记 5
    C++笔记 3
    ipad safari 滚动(overflow)解决方案
    IE9 BUG overflow :auto 底部空白解决方案
    asp.net 导出EXCEL超高兼容(不用装Excel)
    jquery post 同步异步总结
    jquery-alert对话框
    左固定右边自适应框架
    删除Cookies
  • 原文地址:https://www.cnblogs.com/sea-stream/p/10178572.html
Copyright © 2011-2022 走看看