pythonパッキン


1、パラメータなしの包装器
def fun_log(fn):
    def wrapper(*args, **kwargs):
        print "Before Calling %s" %fn.__name__
        retval = fn(*args, **kwargs)
        print "After Calling %s" %fn.__name__
        return retval
    return wrapper


@fun_log    
def greeter(what="world"):
    print "Has excuted!!"
    return "Hello %s" %what

print greeter("You")    

出力:Before Calling greeter Has excuted!!After Calling greeter Hello You
2、パラメータ付き包装器パラメータは文字列である
def fun_log_message(msg):
    print msg
    def wrapper(fn):
        def new_wrapper(*args, **kwargs):
        print ("Before Calling %s" %fn.__name__)
        retval = fn(*args, **kwargs)
        print ("After Calling %s" %fn.__name__)
        return retval
        return new_wrapper
    return wrapper

パラメータは検証関数です.
def validation(arg):
if arg.startswith("log"):
    print "Can LogIn"
    return True
print "cannt LogIn!!"
return False

def root(vali):
    def wrapper(fn):
    def new_wrapper(*args, **kwargs):
        if vali(fn.__name__):
        print "Before Calling %s" %fn.__name__
        retval = fn(*args, **kwargs)
        print "After Calling %s" %fn.__name__
        return retval
    else:
        return
    return new_wrapper
return wrapper

@root(validation)   
def logIn():
    print "Has LogIn!!!"

logIn()