惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

B
Blog RSS Feed
C
CERT Recently Published Vulnerability Notes
P
Proofpoint News Feed
Y
Y Combinator Blog
T
The Blog of Author Tim Ferriss
云风的 BLOG
云风的 BLOG
H
Help Net Security
Recorded Future
Recorded Future
The Register - Security
The Register - Security
F
Full Disclosure
N
Netflix TechBlog - Medium
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
酷 壳 – CoolShell
酷 壳 – CoolShell
H
Hackread – Cybersecurity News, Data Breaches, AI and More
爱范儿
爱范儿
Security Archives - TechRepublic
Security Archives - TechRepublic
Simon Willison's Weblog
Simon Willison's Weblog
Cisco Talos Blog
Cisco Talos Blog
I
InfoQ
T
Tenable Blog
T
Tor Project blog
人人都是产品经理
人人都是产品经理
D
DataBreaches.Net
NISL@THU
NISL@THU
Google DeepMind News
Google DeepMind News
博客园 - 叶小钗
B
Blog
V
V2EX
Jina AI
Jina AI
L
LangChain Blog
月光博客
月光博客
W
WeLiveSecurity
U
Unit 42
AWS News Blog
AWS News Blog
C
Cyber Attacks, Cyber Crime and Cyber Security
博客园 - 聂微东
V
Visual Studio Blog
A
Arctic Wolf
T
Tailwind CSS Blog
The Cloudflare Blog
SecWiki News
SecWiki News
S
SegmentFault 最新的问题
Hacker News - Newest:
Hacker News - Newest: "LLM"
宝玉的分享
宝玉的分享
MyScale Blog
MyScale Blog
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
S
Securelist
www.infosecurity-magazine.com
www.infosecurity-magazine.com
腾讯CDC
雷峰网
雷峰网

Jiajun的技术笔记

你好,2026! TiDB 源码阅读(六):TiDB Coprocessor 源码解析 性能优化的核心思想 TiDB 源码阅读(五):索引 TiDB 源码阅读(四):AST、逻辑计划、物理计划 CockroachDB Serverless Architecture podman 无故退出 Cursor Control-L (CTRL-L) Keyboard Shortcuts in Terminal Replace docker with podman Using xmonad with xfce4 A RC script for freebsd frpc 自己动手写一个k8s controller AI 会取代你的(编程)岗位吗? 自建DERP服务器提升Tailscale连接速度(使用Nginx转发) 自动升级Docker容器 再读《程序员修炼之道-从小工到专家》 让浏览器下载文件 再读《软件随想录》/《黑客与画家》/《软技能》 HTTP 压力测试中的 Coordinated Omission 2的补码 编程语言中的 context 是什么? flutter macOS 构建出错 Flatpak 使用小记 Golang CAS 操作是怎么实现的 PostgreSQL 当MQ来使用 Clash 结合 工作VPN 的网络设计 使用 PostgreSQL 搭建 JuiceFS PostgreSQL 配置优化和日志分析 有GitHub Copilot?那就可以搭建你的ChatGPT4服务 窗口函数的使用(以PG为例) 读《为什么学生不喜欢上学》 OpenAI Prompt Engineering 摘录和总结 读《打造真正的新产品》 VueJS 总结 Linux 自动挂载 alist 提供的webdav FreeBSD 使用 vm-bhyve 安装Debian虚拟机 FreeBSD 和 Linux 网卡聚合实现提速 GPT 帮我搞定了时区转换问题 长任务系统如何处理? macOS/Linux 编译 InputLeap 使用开源软KVM - synergy-core 解决 macOS 终端hostname一直变化问题 KVM 共享 Intel 集成显卡 PromQL 备忘 读《格鲁夫给经理人的第一课》 读《打开心智》 为什么要把复杂的联表操作拆成多个单表查询? 红包系统的设计 MySQL Index Condition Pushdown Optimization Go mod 简明教程 OpenWRT 使用 Android/iOS USB 网络 搭建旁路由 Golang gRPC 错误处理 编写可维护的单元测试代码 OAuth 2 详解(六):Authorization Code Flow with PKCE OAuth 2 详解(五):Device Authorization Flow OAuth 2 详解(三):Resource Owner Password Credentials Grant OAuth 2 详解(四):Client Credentials Flow OAuth 2 详解(二):Implict Grant Flow OAuth 2 详解(一):简介及 Authorization Code 模式 ElasticSearch 学习笔记 三种git流程以及发版模型 错误处理实践 权限模型(RBAC/ABAC) OIDC(OpenID Connect) 简介 任务队列简介 PostgreSQL 操作笔记 使用Drone CI构建CI/CD系统 Golang migrate 做数据库变更管理 使用PostgreSQL做搜索引擎 Nginx 源码阅读(三): 连接池、内存池 Nginx 源码阅读(二): 请求处理 Nginx 源码阅读(一): 启动流程 Go 泛型简明教程 KVM 显卡穿透给 Windows 使用 HTTP Router 处理 Telegram Bot 按钮回调 使用反射(reflect)对结构体赋值 GIN 是如何绑定参数的 你好 2022(2021 年终总结) 用Go导入大型CSV到PostgreSQL 使用 OpenWRT 搭建软路由 使用软KVM切换器 barrier 共享键鼠 SQL 防注入及原理 使用 gomock 测试 Go 代码 gevent不是黑魔法(二): gevent 实现 gevent不是黑魔法(一): greenlet 实现 用 entgo 替代 gorm 应用内使用crontab不是那么方便 单测时要不要 mock 数据库? Sentry 自建指南 用selenium完成自动化任务 用闲置的安卓手机做垃圾电话短信过滤 推荐三个时间管理工具 一次事故反思 当JS遇到uint64:JS整数溢出问题 SQLite3 存储以及ACID原理 Redis源码阅读:pub/sub实现 Redis源码阅读:zset实现 Redis源码阅读:bitmap 位图的运算 Redis源码阅读:set是怎么做交并集运算的?
关于python的decorator和descriptor
2015-12-05 · via Jiajun的技术笔记

一提到python,大家都会说,这门语言很简单。对有编程经验的人来说,python的语法 确实能够在两小时内掌握,但是python这么强大,必然是有一些不那么容易掌握的东西的。

刚学python的时候descriptor,decorator让我感觉有点晕。 不过现在清晰了,于是分享一下我的理解,如有错误,还望不吝赐教。

decorator ~~~~~~~~~

去flask这个web框架的首页一看,就能看到一个例子,例子的内容是这样的:

.. code:: python

from flask import Flask
app = Flask(__name__)

@app.route("/")
def hello():
    return "Hello World!"

if __name__ == "__main__":
    app.run()

| 聪明的你一定一眼就看出来这个例子什么意思,不过上面这个\ @\ 是什么意思呢?学过java | 的朋友可能觉得好像有点眼熟。要注意,我觉得学习一门语言的时候,最大的忌讳就是 | 拿其他语言的语法糖往这门语言上套。

| python中的\ @\ 是一个语法糖,什么叫语法糖?聪明的你此时一定已经打开google搜索了, | 语法糖的存在主要就是为了少打字(懒惰的程序员,哼)。不过上面这个例子的decorator | 有点复杂,在此之前,我们先来看一个简单的decorator:

.. code:: python

def say_hi(func):
    print("hi")

    def wrapper(*args, **kwargs):
        func(args, **kwargs)

    return wrapper


@say_hi
def foo(astr):
    print(astr)

if __name__ == "__main__":
    foo("foo")

执行结果是啥呢?你可以先猜一下再往下看:

.. code:: python

$ python ~/Code/python/fun.py
hi
('foo',)

| 我们知道在python中,函数是可以当做参数传来传去的,就跟C语言里可以把函数地址 | 传来传去一样。之所以说\ @\ 是一个语法糖,是因为根据结果我们可以推测出,执行 | 函数的时候的foo,绝不是我们定义函数时的foo。在\ PEP318 <https://www.python.org/dev/peps/pep-0318/>__ | 有对decorator的详细描述,总结成一句话,就是\ @\ 在上面的例子里相当于 | foo = say_hi(foo)\ ,foo被重新binding成了say_hi里返回的wrapper, | 所以我们会按照say_hi里定义的顺序执行,所以最开始会先打印出”hi”。

| 那flask那个例子是怎么回事呢?能接收参数的decorator。我们就想,\ @app.route | 自己可以接收参数,但同时又要装饰一下下面的hello函数,这怎么做到?hello和app.route | 怎么组合?事实上,可以接收参数的decorator是这样子的:

.. code:: python

def say_sth(arg):
    print(arg)
    def real_decorator(func):
        def wrapper(*args, **kwargs):
            func(*args, **kwargs)
        return wrapper
    return real_decorator

@say_sth("hi")
def foo(astr):
    print(astr)

foo("foo")

执行结果:

.. code:: bash

$ python ~/Code/python/fun.py
hi
foo

另外值得一说,descriptor可以写成class的形式:

.. code:: python

class Dec(object):
    def __init__(self, *args):
        print("__init__")

    def __call__(self, *args):
        print("__call__")


@Dec
def hello():
    print("hello")


if __name__ == "__main__":
    hello()

运行结果是:

.. code:: bash

$ python fun.py
__init__
__call__

| 为什么这里没有打印出hello呢?按照上面所述,\ @\ 那里相当于\ hello = Dec(hello) | 当\ __main__\ 里调用hello()的时候,相当于调用\ Dec.__call__(hello)\ 于是就只执行了 | print("__call__")\ 。可能有同学会有疑问,没有\ __call__\ 行吗?当然可以啦,调用了 | __call__\ 是因为hello后面的括号。你可以把hello()去掉,换成print(hello)试试。

我想看到这里应该已经对decorator有一定的了解了。

descriptor ~~~~~~~~~~

| Python Descriptor HOWTO <https://docs.python.org/3/howto/descriptor.html>__ | 上写的非常清楚,我就不再“抄写”一遍了。

关键点就在:

  • | If the looked-up value is an object defining one of the | descriptor methods, then Python may override the default behavior and invoke | the descriptor method instead. Where this occurs in the precedence chain | depends on which descriptor methods were defined.

  • | Data and non-data descriptors differ in how overrides are calculated with | respect to entries in an instance’s dictionary. | If an instance’s dictionary has an entry with the same name as a data | descriptor, the data descriptor takes precedence. | If an instance’s dictionary has an entry with the same name as a non-data | descriptor, the dictionary entry takes precedence.

所以我们来分析当descriptor和decorator组合起来的例子。

组合


| 在常见的web框架中,为了避免cpu重复计算,一般都会使用或者自己实现一个
| 缓存机制,避免重复计算同一个东西。

下面的代码来自django1.8:

.. code:: python

    class cached_property(object):
        """
        Decorator that converts a method with a single self argument into a
        property cached on the instance.

        Optional ``name`` argument allows you to make cached properties of other
        methods. (e.g.  url = cached_property(get_absolute_url, name='url') )
        """
        def __init__(self, func, name=None):
            self.func = func
            self.__doc__ = getattr(func, '__doc__')
            self.name = name or func.__name__

        def __get__(self, instance, cls=None):
            if instance is None:
                return self
            res = instance.__dict__[self.name] = self.func(instance)
            return res

| 看到代码,\ ``cached_property``\ 是怎么实现的呢?由descriptor一节我们知道,因为没有
| 定义\ ``__set__``\ 方法,所以如果\ ``obj.__dict__``\ 里有名为foo的属性和名为foo被cached\_property
| 装饰的方法,foo会被优先选择。

| 看上面代码中的\ ``__get__``\ 方法,\ ``res = instance.__dict__[self.name] = self.func(instance)``
| 这一行,如果当前实例不为空而且没有叫做name的属性,就会调用到这一行,在实例的
| ``__dict__``\ 中增加一个叫做name的属性,值为\ ``self.func(instance)``\ ,并且同时返回
| 计算结果,当同一个实例再次取叫做name的属性的值的时候,因为已经在\ ``__dict__``\ 中存在,
| 回直接取\ ``__dict__``\ 中的值,不需要再计算一次,从而达到了cache的目的
| (当然了,django中的这个cached\_property还可以用做其他用途,请自己看注释)。

总结

| 好了,简单的总结了“再介绍”了一遍descriptor和decorator,希望能帮到对此感到迷惑的 | 朋友。