当前位置:  开发笔记 > 编程语言 > 正文

Python装饰器在它正在装饰的函数之前运行吗?

如何解决《Python装饰器在它正在装饰的函数之前运行吗?》经验,为你挑选了1个好方法。

举个例子,

def get_booking(f=None):
    print "Calling get_booking Decorator"
    def wrapper(request, **kwargs):
        booking = _get_booking_from_session(request)
        if booking == None:
            # we don't have a booking in our session.
            return HttpRedirect('/')
        else:
            return f(request=request, booking=booking, **kwargs)
    return wrapper

@get_booking
def do_stuff(request, booking):
    # do stuff here

我遇到的问题是,甚至在我调用我正在装饰的函数之前,就会调用@get_booking装饰器.

开始输出:

Calling get_booking Decorator
Calling get_booking Decorator
Calling get_booking Decorator
Calling get_booking Decorator
Calling get_booking Decorator
Calling get_booking Decorator
Calling get_booking Decorator
Calling get_booking Decorator
Calling get_booking Decorator
Calling get_booking Decorator
[26/Oct/2008 19:54:04] "GET /onlinebooking/?id=1,2 HTTP/1.1" 302 0
[26/Oct/2008 19:54:05] "GET /onlinebooking/ HTTP/1.1" 200 2300
[26/Oct/2008 19:54:05] "GET /site-media/css/style.css HTTP/1.1" 200 800
[26/Oct/2008 19:54:05] "GET /site-media/css/jquery-ui-themeroller.css HTTP/1.1" 200 25492

我甚至没有调用此时装饰的函数.

我刚刚开始装饰,所以也许我错过了一些东西.有帮助吗?



1> 小智..:

我相信python装饰器只是语法糖.

@foo
def bar ():
    pass

是一样的

def bar ():
    pass
bar = foo(bar)

正如您所看到的,即使没有调用bar,也会调用foo.这就是你看到装饰器功能的输出的原因.对于应用装饰器的每个函数,您的输出应包含一行.

推荐阅读
mobiledu2402852357
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有