Python重载学习手记
今天学习了一下Python的操作符重载,总结了几点比较神奇的东东:
------------------------------------------------------------------------------------------------------------
关于iter:
Technically, iteration contexts work by calling the iter built-in function to try to
find an _ _iter_ _ method, which is expected to return an iterator object. If it’s
provided,Python then repeatedly calls this iterator object’s next method to produce
items until a StopIteration exception is raised. If no such _ _iter_ _ method is found,
Python falls back on the _ _getitem_ _ scheme, and repeatedly indexes by offsets as
before, until an IndexError exception is raised.
所以为了使用iter,我们必须重载__iter__,然后再定义一个next方法,例子如下:
class Squares:
def _ _init_ _(self, start, stop): # Save state when created
self.value = start - 1
self.stop = stop
def _ _iter_ _(self): # Get iterator object on iter( )
return self
def next(self): # Return a square on each iteration
if self.value == self.stop:
raise StopIteration
self.value += 1
return self.value ** 2
------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------
利用__setattr__的时候,自己赋值不可以使用self.name = value,因为这个语句也是用了__setattr__
,这样重复使用,出错。要使用self.__dict__['name'] = value
------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------
利用__getattr__建立“私有”成员变量:
利用重载的__setattr__在每次取之前判断一下私有成员名字当中有没有,来实现私有,代码如下(取自
Learning Python)
class PrivateExc(Exception): pass
class Privacy:
&nb
相关文档:
使用python.vim使python代码高亮
http://www.vim.org/scripts/script.php?script_id=790
使用
Pydiction插件使vim增加tab代码提示功能
http://www.vim.org/scripts/script.php?script_id=850
具体安装方法可以参照帮助或者README,因为版本变化会导致安装方法上产生差异
编辑~/.vimrc文件增加下面选项
set nu 增加行 ......
对搜索引擎、文件索引、文档转换、数据检索、站点备份或迁移等应用程序来说,经常用到对网页(即HTML文件)的解析处理。事实上,通过Python语言提供的各种模块,我们无需借助Web服务器
或
者Web浏览器就能够解析和处理HTML文档。本文将详细介绍如何利用Python抓取和解析网页。首先,我们介绍一个可以帮助简化打开位于本地和 ......
俄罗斯方块游戏,使用Python实现,总共有350+行代码,实现了俄罗斯方块游戏的基本功能,同时会记录所花费时间,消去的总行数,所得的总分,还包括一个排行榜,可以查看最高记录。
排行榜中包含一系列的统计功能,如单位时间消去的行数,单位时间得分等。
附源码:
from Tkinter import *
from tkMessageBox import *
i ......
原文出处:http://www.amk.ca/python/howto/regex/
原文作者:A.M. Kuchling (amk@amk.ca)
授权许可:创作共享协议
翻译人员:FireHare
校对人员:Leal
适用版本:Python 1.5 及后续版本
简介
Python 自1.5版本起增加了re 模块,它提供 Perl 风格的正则表达式模式。Python 1.5之前版本则是通过 regex
模块提供 ......
Python快速入门
目录
1. 第一章 Python快速入门
&nbs ......