Tchaikov’s Journal

June 4, 2006

Python 的点点滴滴 —— new style class 的 property

Filed under: Python

Python 2.2 引入了 new style class,让撰写 OO 的 class 更为简洁,有的方面可以用上更 pythonic 的解决方案。其中一个重要的改进就是增加了 properties 的设计。既然可以直接访问成员变量,为什么要这些累赘的 getter 和 setter 呢?
要让访问对象的属性操作有更多的灵活性,直接访问对象的数据成员的办法明显有些襟。因此必须通过 getter 和 setter 来包装。因为有的属性无法与对象的成员变量直接对应。它(这类属性)有可能就是需要临时计算得到。比如一个有序队列的最大值。
第一次看到 property 是在 Delphi (Object Pascal)里。语法和 Python 惊人的相似:

 Property Top    : Longint Index 1 read GetCoord write SetCoord;

Python 里则是

top = property(fget=get_coord, fset=set_coord)

但是要注意的是,new style class 必须继承自 object,否则,当我们高高兴兴地使用 foo.top = 1 的时候,get_coord 是不会被调用的,虽然 Python 一声不吭地接受了你的 property 声明(它的确没有 warning,或者类似 property statement is only available in new style class 的错误警告)。但是,foo.top = 1,仅仅是执行了 foo.__dict__[’top’] = 1 的操作,不多也不少。

Comments »

The URI to TrackBack this entry is: http://tchaikov.blogsome.com/2006/06/04/p30/trackback/

No comments yet.

RSS feed for comments on this post.

Leave a comment

Line and paragraph breaks automatic, e-mail address never displayed, HTML allowed: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <code> <em> <i> <strike> <strong>


Get free blog up and running in minutes with Blogsome
Theme designed by Jay of onefinejay.com