search

项目地址: https://git.io/pytips

Python 的修饰器是一种语法糖(Syntactic Sugar),也就是说:

@decorator@wrapdef func():    pass

是下面语法的一种简写:

def func():    passfunc = decorator(wrap(func))

关于修饰器的两个主要问题:

  1. 修饰器用来修饰谁

  2. 谁可以作为修饰器

修饰函数

修饰器最常见的用法是修饰新定义的函数,在 0x0d 上下文管理器 中提到上下文管理器主要是为了 更优雅地完成善后工作 ,而修饰器通常用于扩展函数的行为或属性:

def log(func):    def wraper():        print("INFO: Starting {}".format(func.__name__))        func()        print("INFO: Finishing {}".format(func.__name__))    return wraper@logdef run():    print("Running run...")run()
INFO: Starting runRunning run...INFO: Finishing run

修饰类

除了修饰函数之外,Python 3.0 之后增加了对新定义类的修饰( PEP 3129 ),但是对于类别属性的修改可以通过 Metaclasses 或继承来实现,而新增加的类别修饰器更多是出于 Jython 以及 IronPython 的考虑,但其语法还是很一致的:

from time import sleep, timedef timer(Cls):    def wraper():        s = time()        obj = Cls()        e = time()        print("Cost {:.3f}s to init.".format(e - s))        return obj    return wraper@timerclass Obj:    def __init__(self):        print("Hello")        sleep(3)        print("Obj")o = Obj()
HelloObjCost 3.005s to init.

类作为修饰器

上面两个例子都是以函数作为修饰器,因为函数才可以被调用(callable) decorator(wrap(func)) 。除了函数之外,我们也可以定义可被调用的类,只要添加 __call__ 方法即可:

class HTML(object):    """        Baking HTML Tags!    """    def __init__(self, tag="p"):        print("LOG: Baking Tag <{}>!".format(tag))        self.tag = tag    def __call__(self, func):        return lambda: "<{0}>{1}</{0}>".format(self.tag, func(), self.tag)@HTML("html")@HTML("body")@HTML("div")def body():    return "Hello"print(body())
LOG: Baking Tag <html>!LOG: Baking Tag <body>!LOG: Baking Tag <div>!<html><body><div>Hello</div></body></html>

传递参数

在实际使用过程中,我们可能需要向修饰器传递参数,也有可能需要向被修饰的函数(或类)传递参数。按照语法约定,只要修饰器 @decorator 中的 decorator 是可调用即可, decorator(123) 如果返回一个新的可调用函数,那么也是合理的,上面的 @HTML('html') 即是一例,下面再以 flask 的路由修饰器为例说明如何传递参数给修饰器:

RULES = {}def route(rule):    def decorator(hand):        RULES.update({rule: hand})        return hand    return decorator@route("/")def index():    print("Hello world!")def home():    print("Welcome Home!")home = route("/home")(home)index()home()print(RULES)
Hello world!Welcome Home!{'/': <function index at 0x10706f730>, '/home': <function home at 0x10706f8c8>}

向被修饰的函数传递参数,要看我们的修饰器是如何作用的,如果像上面这个例子一样未执行被修饰函数只是将其原模原样地返回,则不需要任何处理(这就把函数当做普通的值一样看待即可):

@route("/login")def login(user = "user", pwd = "pwd"):    print("DB.findOne({{{}, {}}})".format(user, pwd))login("hail", "python")
DB.findOne({hail, python})

如果需要在修饰器内执行,则需要稍微变动一下:

def log(f):    def wraper(*args, **kargs):        print("INFO: Start Logging")        f(*args, **kargs)        print("INFO: Finish Logging")    return wraper@logdef run(hello = "world"):    print("Hello {}".format(hello))run("Python")
INFO: Start LoggingHello PythonINFO: Finish Logging

functools

由于修饰器将函数(或类)进行包装之后重新返回: func = decorator(func) ,那么有可能改变原本函数(或类)的一些信息,以上面的 HTML 修饰器为例:

@HTML("body")def body():    """        return body content    """    return "Hello, body!"print(body.__name__)print(body.__doc__)
LOG: Baking Tag <body>!<lambda>None

因为 body = HTML("body")(body) ,而 HTML("body").__call__() 返回的是一个 lambda 函数,因此 body 已经被替换成了 lambda ,虽然都是可执行的函数,但原来定义的 body 中的一些属性,例如 __doc__ / __name__ / __module__ 都被替换了(在本例中 __module__ 没变因为都在同一个文件中)。为了解决这一问题 Python 提供了 functools 标准库,其中包括了 update_wrapper 和 wraps 两个方法( 源码 )。其中 update_wrapper 就是用来将原来函数的信息赋值给修饰器中返回的函数:

from functools import update_wrapper"""functools.update_wrapper(wrapper, wrapped[, assigned][, updated])"""class HTML(object):    """        Baking HTML Tags!    """    def __init__(self, tag="p"):        print("LOG: Baking Tag <{}>!".format(tag))        self.tag = tag    def __call__(self, func):        wraper = lambda: "<{0}>{1}</{0}>".format(self.tag, func(), self.tag)        update_wrapper(wraper, func)        return wraper@HTML("body")def body():    """        return body content!    """    return "Hello, body!"print(body.__name__)print(body.__doc__)
LOG: Baking Tag <body>!body        return body content!    

有趣的是 update_wrapper 的用法本身就很像是修饰器,因此 functools.wraps 就利用 functools.partial (还记得函数式编程中的偏应用吧!)将其变成一个修饰器:

from functools import update_wrapper, partialdef my_wraps(wrapped):    return partial(update_wrapper, wrapped=wrapped)def log(func):    @my_wraps(func)    def wraper():        print("INFO: Starting {}".format(func.__name__))        func()        print("INFO: Finishing {}".format(func.__name__))    return wraper@logdef run():    """    Docs' of run    """    print("Running run...")print(run.__name__)print(run.__doc__)
run    Docs' of run    

欢迎关注公众号 PyHub!

参考

  1. Python修饰器的函数式编程

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Difficulty in updating caching of official account web pages: How to avoid the old cache affecting the user experience after version update?Difficulty in updating caching of official account web pages: How to avoid the old cache affecting the user experience after version update?Mar 04, 2025 pm 12:32 PM

The official account web page update cache, this thing is simple and simple, and it is complicated enough to drink a pot of it. You worked hard to update the official account article, but the user still opened the old version. Who can bear the taste? In this article, let’s take a look at the twists and turns behind this and how to solve this problem gracefully. After reading it, you can easily deal with various caching problems, allowing your users to always experience the freshest content. Let’s talk about the basics first. To put it bluntly, in order to improve access speed, the browser or server stores some static resources (such as pictures, CSS, JS) or page content. Next time you access it, you can directly retrieve it from the cache without having to download it again, and it is naturally fast. But this thing is also a double-edged sword. The new version is online,

How do I use HTML5 form validation attributes to validate user input?How do I use HTML5 form validation attributes to validate user input?Mar 17, 2025 pm 12:27 PM

The article discusses using HTML5 form validation attributes like required, pattern, min, max, and length limits to validate user input directly in the browser.

What are the best practices for cross-browser compatibility in HTML5?What are the best practices for cross-browser compatibility in HTML5?Mar 17, 2025 pm 12:20 PM

Article discusses best practices for ensuring HTML5 cross-browser compatibility, focusing on feature detection, progressive enhancement, and testing methods.

How to efficiently add stroke effects to PNG images on web pages?How to efficiently add stroke effects to PNG images on web pages?Mar 04, 2025 pm 02:39 PM

This article demonstrates efficient PNG border addition to webpages using CSS. It argues that CSS offers superior performance compared to JavaScript or libraries, detailing how to adjust border width, style, and color for subtle or prominent effect

What is the purpose of the <datalist> element?What is the purpose of the <datalist> element?Mar 21, 2025 pm 12:33 PM

The article discusses the HTML <datalist> element, which enhances forms by providing autocomplete suggestions, improving user experience and reducing errors.Character count: 159

What is the purpose of the <meter> element?What is the purpose of the <meter> element?Mar 21, 2025 pm 12:35 PM

The article discusses the HTML <meter> element, used for displaying scalar or fractional values within a range, and its common applications in web development. It differentiates <meter> from <progress> and ex

How do I use the HTML5 <time> element to represent dates and times semantically?How do I use the HTML5 <time> element to represent dates and times semantically?Mar 12, 2025 pm 04:05 PM

This article explains the HTML5 <time> element for semantic date/time representation. It emphasizes the importance of the datetime attribute for machine readability (ISO 8601 format) alongside human-readable text, boosting accessibilit

What is the purpose of the <progress> element?What is the purpose of the <progress> element?Mar 21, 2025 pm 12:34 PM

The article discusses the HTML <progress> element, its purpose, styling, and differences from the <meter> element. The main focus is on using <progress> for task completion and <meter> for stati

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool