Python装饰器?- 有人可以解释一下吗? [英] Python decorator? - can someone please explain this?

查看:62
本文介绍了Python装饰器?- 有人可以解释一下吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

抱歉,这是一个非常广泛的问题.

Apologies this is a very broad question.

下面的代码是在网上找到的一些东西的片段.我感兴趣的关键是@protected 开头的行 - 我想知道这是做什么以及它是如何做的?它似乎是在执行 do_upload_ajax 函数之前检查有效用户是否已登录.这看起来是进行用户身份验证的一种非常有效的方法.我不明白这个@ 函数的机制 - 有人能引导我朝着正确的方向解释这将如何在现实世界中实现吗?请回答 Python 3.谢谢.

The code below is a fragment of something found on the web. The key thing I am interested in is the line beginning @protected - I am wondering what this does and how it does it? It appears to be checking that a valid user is logged in prior to executing the do_upload_ajax function. That looks like a really effective way to do user authentication. I don't understand the mechanics of this @ function though - can someone steer me in the right direction to explain how this would be implemented in the real world? Python 3 answers please. thanks.

@bottle.route('/ajaxupload', method='POST')
@protected(check_valid_user) 
def do_upload_ajax():
    data = bottle.request.files.get('data')
    if data.file:
        size = 0

推荐答案

好好看看这个 good巨大的答案/小说.这是我遇到的最好的解释之一.

Take a good look at this enormous answer/novel. It's one of the best explanations I've come across.

我能给出的最简短的解释是装饰器将您的函数包装在另一个返回函数的函数中.

The shortest explanation that I can give is that decorators wrap your function in another function that returns a function.

这段代码,例如:

@decorate
def foo(a):
  print a

如果删除装饰器语法,则相当于此代码:

would be equivalent to this code if you remove the decorator syntax:

def bar(a):
  print a

foo = decorate(bar)

装饰器有时会接受参数,这些参数会传递给动态生成的函数以更改其输出.

Decorators sometimes take parameters, which are passed to the dynamically generated functions to alter their output.

您应该阅读的另一个术语是闭包,因为这是允许装饰器工作的概念.

Another term you should read up on is closure, as that is the concept that allows decorators to work.

这篇关于Python装饰器?- 有人可以解释一下吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆