常用函数介绍:
help(“sys”) | 函数的hlep文档 |
range(end) range (start, end) range (start, end, step) | range(10) 表示0…9 |
dir() | 当前命名空间的所有标识符 |
len(“hi”) | 序列的长度 |
“str” * intValue | “a” * 3 得到“aaa” |
raise excName, excInfo | 抛异常 |
issubclass(class, fatherClass) | 是否子类关系 |
isinstance(object, class) | 是否为类的实例对象 |
__getattr__
__getattribute__ | 访问一个属性名,先在__dict__属性找,找不到再到这个方法里找. 每次访问属性都会执行它。重写要调用基类的方法,用__dict__回无穷递归(用__dict__属性也会调此方法)。 注释:当obj.Attr来访问,先执行__getattribute__方法,或再执行__getattr__ |
ord(“z”) | 返回字符的unicode代码 |
string的center(空格数),rjust(空格数),ljust(空格数) | 字符串的格式化:居中,左,右对齐 |
string的strip (),lstrip (),rstrip () | 字符串的去掉空格和换行符 |
import os os.environ.keys(): os.getcwd() os.chdir(‘c:\\a\\b’) | 得到OS操作系统的信息 得到当前目录
|
import csv csv.reader(u) | 读取CSV文件的内容,或者处理字符串 |
eval(str) | 可以把格式”str”变成str。 |
type (obj) | 判断属于类 |
常用常量介绍:
__name__ | 模块名,比如 "__main__" |
__bases__ | 显示类的直接父类及其内存等信息 |
__dict__ | 返回以字典,值为命名空间所有标识符 |
__slots__ | 类中列出所有允许包含的属性。否则会抛异常。会给未赋值的赋值为None。 |
|
|
示范代码:
def gcd( x, y ): while y: z = x x = y y = z % y
return x | 求最大公约数 |
import urllib import re
def gethtmlSource(): tempFile = urllib.urlopen( "http://image.baidu.com/" ) strPageSource = tempFile.read() return strPageSource def getimage(htmlSource): pattern = re.compile(r'"src": "(http.*?jpg)","url"') imglist = re.findall(pattern, htmlSource) iimge = 0 for oneulr in imglist: oneulr = re.sub(r"\\", "", oneulr) iimge += 1 urllib.urlretrieve(oneulr, "C:/\ image/\%s.jpg" % iimge)
getimage (gethtmlSource()) | 一个小爬虫的小程序。 |
from tkMessageBox import showwarning warn = lambda excel: showwarning(excel, 'Exit?') warn(‘excel’) | 弹出对话框 |