TE
科技回声
首页24小时热榜最新最佳问答展示工作
GitHubTwitter
首页

科技回声

基于 Next.js 构建的科技新闻平台,提供全球科技新闻和讨论内容。

GitHubTwitter

首页

首页最新最佳问答展示工作

资源链接

HackerNews API原版 HackerNewsNext.js

© 2025 科技回声. 版权所有。

Python decorators: A neat way to modify functions

4 点作者 fogus大约 13 年前

1 comment

saurik大约 13 年前
It is a crying shame that this article fails to realize that decorator.decorator is itself a decorator, and that failing to use it as such undermines the premise that decorators are "a neat way to modify functions". With this realization:<p><pre><code> @decorator.decorator def heading1(func, *args, **kwargs): return "&#60;h1&#62;" + func(*args, **kwargs) + "&#60;/h1&#62;" </code></pre> With this construction, you no longer need to have the two copies of the function: the degenerate wrapper can be removed and replaced with this decorator.<p>Even if the library didn't provide this, you can just look at this code and feel "no, wait, this is wrong: this should be implemented with a decorator" and write this:<p><pre><code> def better_decorator(function): def wrapped(function, *args, **kw): return decorator.decorator(function, *args, **kw) return decorator.decorator(wrapped, function) </code></pre> This new decorator, @better_decorator, can now be used in place of @decorator.decorate in the above example, and again solves the problem of the degenerate wrapper by generalizing it into a single universal degenerate wrapper.
评论 #3796749 未加载