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

  • 相关阅读:
    利用MFC获取网页内容
    IP地址 >实际地址 ,API 查询
    一个小时内学习 SQLite 数据库
    Sqlite c/c++ api 学习
    笔记
    Sqlite的操作(增加,删除,查询,修改)
    免费天气API
    ServerSocketChannel的使用例子
    各种模式一览
    什么事文件描述符
  • 原文地址:https://www.cnblogs.com/sea-stream/p/10178572.html
Copyright © 2011-2022 走看看