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

    1.

    >>> def deco(func):
    ...     print "In deco"
    ...     return func
    ...
    >>> @deco
    ... def foo():
    ...     print "In foo"
    ...
    In deco                 #因为deco()返回的 func 本身
    >>>

    >>>foo()
    In foo

    2.改进

    >>> def deco(func):
    ...    print "in deco"
    ...    def wrapper():
    ...         print "wrapper start"
    ...         func()
    ...         print "wrapper end"
    ...    return wrapper
    ...
    >>>
    >>> @deco
    ... def foo():
    ...   print "foo"
    ...
    in deco
    >>>
    >>>
    >>> foo()
    wrapper start
    foo
    wrapper end

    在非交互模式下输出:

    in deco
    wrapper start
    foo
    wrapper end

    3.怎么装饰不同参数的多个函数

    def deco(func):
        def wrapper(*args, **kwargs):
            print "Wrap start"
            func(*args, **kwargs)
            print "Wrap end"
        return wrapper
    
    @deco
    def foo(x):
        print "In foo():"
        print "I have a para: %s" % x
    
    @deco
    def bar(x,y):
        print "In bar():"
        print "I have two para: %s and %s" % (x, y)
    
    @deco
    def foo_dict(x,z='dict_para'):
        print "In foo_dict:"
        print "I have two para, %s and %s" % (x, z)
    
    if __name__ == "__main__":
        foo('x')
        bar('x', 'y')
        foo_dict('x', z='dict_para')

    4.让装饰函数名更有意义些:带参数的装饰函数

    def deco(arg):
        def _deco(func):
            def wrapper():
                print("before %s called [%s]." % (func.__name__, arg))
                func()
                print("after %s called [%s]." % (func.__name__, arg))
            return wrapper
        return _deco
     
    @deco("module1")             #可以填插入类型
    def insert_balance():
        print("insert into balance")
     
    @deco("module2")
    def insert_customer():
        print("insert into customer")
  • 相关阅读:
    String.prototype.getParm
    IOS—通过ChildViewController实现view的切换
    objective-c IBOutletCollection介绍
    iOS方法类:CGAffineTransform的使用大概
    cocoaPods下载使用记录
    objective-c 中的关联介绍
    操作系统--文件管理
    操作系统--设备管理
    操作系统--存储管理的任务
    操作系统--并发进程死锁
  • 原文地址:https://www.cnblogs.com/yuyutianxia/p/4116082.html
Copyright © 2011-2022 走看看