装饰器在装饰函数之前运行

装饰器在装饰函数之前运行

本文介绍了装饰器在装饰函数之前运行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如:

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装饰器

The problem I am having is, the @get_booking decorator is being called even before I called the function that I am decorating.

启动时的输出:

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

我现在还没有调用装饰过的函数。

I haven't even made a call to a function that is decorated at this point.

我刚刚开始使用装饰器,所以也许我错过了一些东西。

I am just getting started with decorators, so maybe I am missing something.

推荐答案

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

I believe python decorators are just syntactic sugar.

@foo
def bar ():
    pass

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

如您所见,即使没有调用 bar ,也正在调用 foo 。这就是为什么您看到装饰器函数的输出的原因。对于您将装饰器应用到的每个函数,您的输出应包含一行。

As you can see, foo is being called even though bar has not been called. This is why you see the output from your decorator function. Your output should contain a single line for every function you applied your decorator to.

这篇关于装饰器在装饰函数之前运行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 01:40