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

推荐订阅源

T
Tor Project blog
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
T
Threatpost
T
Troy Hunt's Blog
O
OpenAI News
S
Securelist
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
P
Proofpoint News Feed
S
Secure Thoughts
Martin Fowler
Martin Fowler
H
Hacker News: Front Page
博客园_首页
Security Latest
Security Latest
Cyberwarzone
Cyberwarzone
阮一峰的网络日志
阮一峰的网络日志
L
LINUX DO - 热门话题
V2EX - 技术
V2EX - 技术
W
WeLiveSecurity
雷峰网
雷峰网
博客园 - Franky
C
Cyber Attacks, Cyber Crime and Cyber Security
Jina AI
Jina AI
S
Security @ Cisco Blogs
Apple Machine Learning Research
Apple Machine Learning Research
S
Security Affairs
Scott Helme
Scott Helme
T
The Exploit Database - CXSecurity.com
博客园 - 三生石上(FineUI控件)
P
Privacy & Cybersecurity Law Blog
罗磊的独立博客
G
Google Developers Blog
L
Lohrmann on Cybersecurity
量子位
The GitHub Blog
The GitHub Blog
V
Vulnerabilities – Threatpost
大猫的无限游戏
大猫的无限游戏
T
Threat Research - Cisco Blogs
K
Kaspersky official blog
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
Webroot Blog
Webroot Blog
F
Fortinet All Blogs
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
小众软件
小众软件
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
GbyAI
GbyAI
PCI Perspectives
PCI Perspectives
N
News | PayPal Newsroom
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
Spread Privacy
Spread Privacy
有赞技术团队
有赞技术团队

卡瓦邦噶!

服务器高性能网络调优 | 卡瓦邦噶! 为何写作 | 卡瓦邦噶! 读《金阁寺》 | 卡瓦邦噶! 雨季又来 | 卡瓦邦噶! MTU Probe 引起的初始延迟 | 卡瓦邦噶! 3.5 秒的固定延迟问题 | 卡瓦邦噶! 学习网络的一点经验 | 卡瓦邦噶! ARP 问题诊断 | 卡瓦邦噶! 网络断断续续…… | 卡瓦邦噶! Piccolo P2P 镜像分发 | 卡瓦邦噶! 一起看电影 | 卡瓦邦噶! 《征服C指针》 | 卡瓦邦噶! 我的姥姥 | 卡瓦邦噶! Python的哲学 Python 3.5的新特性 学校不教的计算机课 垃圾回收(GC)的三种基本方式 在编程中体验纯粹的快乐 从《美丽新世界》谈自由 在快钱实习 迷人的嗓音和迷人的故事——《Sleepyhead》 Python 的十个自然语言处理工具 记一个愚蠢的bug 一年炉石传说的游戏体验 《以撒的结合:重生》网页版图鉴 分清 C++的指针、引用和数组 笑话三则 自由比皇帝更伟大——《悲惨世界》笔记 Git 10 周年访谈:Linus 讲述背后故事 用 0x3f3f3f3f 设定最大int值的优点 Joel给计算机系学生的建议 一个词法分析器的简单实现 怎样才算健康的生活方式 MacVim 配置攻略 学习培训课程的视频效果好吗? 语言的控制 可悲的大多数 CSS样式思维导图 2014年终总结 奥巴马成为首位写程序的美国总统 青岛老城区的下水道好在哪里? 做优秀 UI 的七个建议(第二部分) 选择爱情的骑士 Git简明教程 Java集合总览 读 《1984》 java问答:终极父类(六)——等待/唤醒和接口 Java 问答:终极父类(五)——toString() Hyperlapse快速视频背后的技术细节 平庸之恶 Java程序员须知的七个日志管理工具 苏州 逛书摊随想 关于考试作弊 你的工作不仅仅是编程 推荐在线学习Java的英文资源 关注女性命运——《千禧年三部曲》 用好你的幻灯片——《演说之禅》 使用ReentrantLock和Lambda表达式让同步更纯净 新手学编程,从哪里开始? 程序员都是工程师吗? 不要学习代码,要学会思考 Java 问答:终极父类(四)——hashCode() Java 问答:终极父类(三)——finalize()和 getClass() 程序员职业之路的选择 我是一名摄影家 写给何小树的城市指南 为什么一些语言会比别的快? Java的常见误区与细节 跟朋友在一起玩游戏 死神永生——读《三体》 五种类型的程序员 创业圣经——读《黑客与画家》 纪念加西亚·马尔克斯 Junit中处理异常的另一种方式:catch-exception Java8采用Martin Fowler的方法创建内部DSL Linux HotSopt虚拟机GC线程的CPU占用率 J2EE概念介绍 如何成为一名黑客 Java 问答:终极父类(二)——equals()方法 为什么我喜欢Java Java 问答:终极父类(一)——clone()方法 七个改变世界的Java项目 java中默认类型转换的小问题 传统与创新 欢迎来到互联网 莫言和马尔克斯——读《生死疲劳》 位运算的妙用 读《人为什么活着》 写博客教会我的事情 中国特色操作系统 2013年总结 《永不妥协》影评 恨不相逢未嫁时——《廊桥遗梦》影评 如何优雅地使用PPT 给明年依然年轻的我们 天才与柱子 黑客守则和黑客精神 Looking for Freedom——《被解救的姜戈》 简洁之道
Python 实现class_property
laixintao · 2017-11-01 · via 卡瓦邦噶!

Python的property可以让我们很方便地将一个object的函数当做一个属性来操作,可以赋值、读取。

Python

1

2

3

4

5

6

7

8

9

10

11

12

class Parrot:

    def __init__(self):

        self._voltage = 100000

    @property

    def voltage(self):

        """Get the current voltage."""

        return self._voltage

p = Parrot()

p.voltage

# 100000

但是不支持class,如果想使用这个特性,就要实例化对象。我去参考了celery实现的class_property,发现有一行特别难懂,花了很长时间琢磨,终于是看懂了。

celery的代码如下:

Python

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

class class_property(object):

    def __init__(self, getter=None, setter=None):

        if getter is not None and not isinstance(getter, classmethod):

            getter = classmethod(getter)

        if setter is not None and not isinstance(setter, classmethod):

            setter = classmethod(setter)

        self.__get = getter

        self.__set = setter

        info = getter.__get__(object)  # just need the info attrs.

        self.__doc__ = info.__doc__

        self.__name__ = info.__name__

        self.__module__ = info.__module__

    def __get__(self, obj, type=None):

        if obj and type is None:

            type = obj.__class__

        return self.__get.__get__(obj, type)()

    def __set__(self, obj, value):

        if obj is None:

            return self

        return self.__set.__get__(obj)(value)

    def setter(self, setter):

        return self.__class__(self.__get, setter)

使用方法如下:

Python

1

2

3

4

5

6

7

class Logging:

    @class_property

    def already_setup(self):

        return True

Logging.already_setup

# True

这段代码能work,而是没有任何问题。装饰在class内的一个函数上,可以将此函数的返回值作为一个class的属性,可以通过class和instance来访问,并且还支持setter。

首先,__init__()比较好理解,传入getter和setter,将其转换为classmethod然后绑定到内部的变量上,以便后来调用。

setter()方法也比较好理解,可以当做装饰器调用, 然后已有的self.__get和传入的setter重新初始化一个class_property,如果已经有getter的话,这里也不会对getter造成影响。参考下面的例子:

Python

1

2

3

@already_setup.setter  # noqa

   def already_setup(self, was_setup):

       self._setup = was_setup

然后看__get____set__方法,很明显,这里使用的描述器。(关于描述器,我之前有一篇博文详细讲了描述器——理解Python对象的属性和描述器。)第一个if判断是为了确保用class_property装饰的属性通过instance也能访问到。

最后到了最让人不理解的部分了,如果要我实现的话,是直接返回getter就可以了:

return self.__get()

这样看起来也没问题:访问Logging类的时候,发现没有这个already_setup这个属性,然后试图访问描述器,描述器__get__()中返回self.__get()不正好是getter会返回的结果吗?

于是我将这行return改成了上面我的意思,结果报错:

Python

1

2

3

4

5

6

7

8

9

10

11

12

13

---------------------------------------------------------------------------

TypeError                                 Traceback (most recent call last)

<ipython-input-20-6db509700877> in <module>()

----> 1 class_property(Logging.already_setup)()

<ipython-input-14-9345a093811c> in __get__(self, obj, type)

     20         print(self.__get)

     21         print(self.__get.__get__(obj, type))

---> 22         return self.__get(obj)

     23

     24     def __set__(self, obj, value):

TypeError: 'classmethod' object is not callable

classmethod为什么不是callable的呢?因为classmethod本来就不是callable的!在之前的文章中,我模拟了classmethod的实现:

Python

1

2

3

4

5

6

7

8

9

10

11

12

class ClassMethod(object):

    "Emulate PyClassMethod_Type() in Objects/funcobject.c"

    def __init__(self, f):

        self.f = f

    def __get__(self, obj, klass=None):

        if klass is None:

            klass = type(obj)

        def newfunc(*args):

            return self.f(klass, *args)

        return newfunc

它的原理是这样的:Class读一个属性的时候,如果Class.__dict__有该属性并且属性不是一个描述器,就返回该属性;如果该属性是一个描述器,就调用它的__get__方法。

举个例子说,下面的代码:

Python

1

2

3

4

5

6

7

class Foo:

    @classmethod

    def bar(cls):

        return "hello"

Foo.bar()

# hello

在调用的时候,先看Foo.__dict__里面的bar是一个描述器,那么调用就转换成:

Foo.__dict__['bar'].__get__(None, Foo)()

回到我们的class_property上来,拿最初的Logging举例。用了class_property装饰的already_setup使用起来(Logging.already_setup)就是:

Logging.__dict__['already_setup'].__get__(None, Logging)()

执行我们的class_property的__get__之后,也就是

Logging.__dict__['already_setup'].__get()

此时,橙色的部分拿到的是一个class_property处理之后的classmethod,而上面我们可以看到,classmethod并不是callable的,而是通过描述器协议,class在调用的时候会默认调用__get__,然后拿到一个和class绑定之后的func,这时候的func才是可以调用的。

celery里面原来写的return,调用链展开就是:

Logging.__dict__['already_setup'].__get.__get__(obj, type)()

其中橙色的部分依然是拿到了classmethod,即:

Logging.classmethod_get.__get__(obj, type)()

classmethod的__get__()返回的是一个unbound method,即

Logging.already_setup()

这样调用就没问题了。

所以说,这里手动调用__get__(obj, type)的原因是,描述器协议之能调用一次,如果返回的还是一个描述器,那么并不会继续调用__get__方法,需要手动调用。