gpt4 book ai didi

python - 装饰器在它装饰的函数被调用之前运行?

转载 作者:太空狗 更新时间:2023-10-29 19:31:24 25 4
gpt4 key购买 nike

举个例子:

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

此时我什至还没有调用装饰过的函数。

我刚刚开始使用装饰器,所以我可能遗漏了一些东西。

最佳答案

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

@foo
def bar ():
pass

是一样的
def bar ():
pass
bar = foo(bar)

如您所见,尽管 bar 尚未调用,但正在调用 foo。这就是为什么您会看到装饰器函数的输出。对于您应用了装饰器的每个函数,您的输出应该包含一行。

关于python - 装饰器在它装饰的函数被调用之前运行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/341379/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com