http://doc.chinahtml.com/Manual/Python/tut/node2.html
前言
名称起源:BBC的“Monty Python’s Flying Circus”节目,
Python是一门解释性脚本语言,
面向对象,
语句组织依赖于缩进而不是{}或者begin/end,
不需要声明变量或者参数。
Python解释器
调用解释器
1.直接启动:
[perfectworks@Debian ~]# python
2.调用脚本:
[perfectworks@Debian ~]# python script
3.直接运行语句:
[perfectworks@Debian ~]# python -c command[arg]…
参数传递:sys.argv[0]脚本名,sys.argv[1]第一个参数。
多行结构:主提示符:<<<,从属提示符...
Python脚本
单行注释:#
开头写入:
编码指定:
1
| # -*- coding: utf-8 -*- |
不直接支持GB/GBK/GB18030/ISO-10646(新版好像有所改进?)
运算
直接支持整数/浮点/复数运算,可以用变量_调出上一次的运算结果。
>>> tax = 12.5 / 100
>>> price = 100.50
>>> price * tax
12.5625
>>> price + _
113.0625
>>> round(_, 2)
113.06
>>>
字符串与运算
单引号,双引号,三引号,
字符串分行,行末加\,
三引号与raw行:保留一切格式,行末不需加\。
字符串用+连接,用*循环,用[a:b]切出部分字符串。
字符串长度:len(str)。
Unicode字符串,引号前加u,可以用Unicode代码输入。
链表
类似数组,用中括号[]标记以逗号分隔的一系列值。
可以当做堆栈/队列使用。
链表方法:
append(x)
extend(x)
insert(i,x)
remove(x)
pop([i])
index(x)
count(x)
sort()
reverse()
filter(),返回调用函数后为true的元素;
map(),返回调用函数后的所有结果;
reduce(),调用前一次的处理结果作为下一次运算的函数参数。
链表推导式:[function(x) for x in linkList],将linkList中的每一个元素作为function的参数传入后,将返回结果输出。
元组(Tuples),序列(Sequences)
用小括号围住,以逗号分割。元组是不可改变的链表。
序列拆封:
>>> t = 12345,54321,'hello'
>>> x,y,z = t
字典(Dictionaries)
Hash表,用大括号围住,以逗号分隔,’key’:value对
循环
1
2
3
4
5
6
| for key,value in dict.itmes():
print k,v
for pos,value in enumerate(array):
print pos,value
for valueA,valueB in zip(arrayA,arrayB):
print valueA,valueB |
流程控制
1
2
3
4
5
6
| if a>b:
print a
elif a==b:
print a
else:
pass |
函数
1
2
3
4
5
6
| def func(love,qmt="beauty")
return love
func(love="yc")
func("yc") |
赋值失败:缺少必要参数,关键字后面出现非关键字赋值,参数重复赋值,未知关键字
模块
1
2
3
4
5
6
7
| import package # 引入package.py
package.test() # 调用package.py中的test函数
from package import * # 导入模块快定义中所有命名
test() # 调用了package.test()
dir(package) # 返回package中所有的定义
import package.pkg # 引入/package/pkg.py,package目录下比如有__init__.py |
输入输出
格式化字符串,str()与repr()
格式化输出 print ‘%2d %3d %4d’ % (x,x*x,x*x*x)
文件读写
1
2
3
4
5
6
7
8
| fp = open('filename','mode')
fp.read()
fp.readline()
fp.readlines()
fp.write(string)
fp.tell()
fp.seek()
fp.close() |
数据类型的序量化:
1
2
| pickle.dump(obj,fp)
obj = pickle.load(fp) |
错误处理
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
| class ImpossibleError(Exception): # 自定义错误类
def __init__(self,value):
self.value = value
def __str__(self):
return repr(self.value)
try:
print "trying"
raise ImpossibleError, 'nothing is impossible!' # 强制抛出异常
break
except ImpossibleError: # except加类名,捕获异常
print "that's impossible"
except: # 捕获所有异常
print "that's impossible,too"
try:
print "trying"
raise ImpossibleError, 'nothing is impossible!'
break
finally:
print "the impossible thing will happen" # 无论try是否有异常都会被执行 |
类
1
2
3
4
5
6
7
8
9
10
11
12
13
| class MyClass: # 定义一个类
def __int__(self): # 构造函数
pass
def __iter__(self): # 迭代器
return self
def next(self):
if self.index == 0:
raise StopIteration
self.index = self.index - 1
return self.data[self.index]
class MyClass2rd(MyClass): # 继承
def __int__(self): # 构造函数
pass |
python支持多继承
发生器看的不是很明白
结束
不是结束,而是开始
Script
python
最新评论