资讯专栏INFORMATION COLUMN

Python入门指引

YacaToy / 2414人阅读

摘要:或者输入调用模块模块也就是源文件进入交互命令模式参数传递命令行的参数会赋值给模块的变量。操作符是向下取数,小数位为。每一个脚本文件称之为一个模块。

Python是比较热的语言,个人兴趣参考官方文档:https://docs.python.org/2/tut...
边看边翻译了一下(后面会持续更新),有兴趣的可以看看。

Python具有高级的数据结构,能高效地面向对象编程。它的优雅的语法、动态类型、解释属性使它能快速地在大部分平台开发应用程序。它的第三方包、工具和库都可以在这里找到:https://www.python.org/。

Python很容易通过C/C++函数或数据类型进行扩展。写扩展参看:扩展指导, C/C++的Python API

更多文档参看Python标准库,Python的API

通过这个入门教程,你将学习到Pyton的一些常用特性和标准库的一些方法或模块。

写在前面

对于每天在电脑面前工作的人来说,可能你需要做一些自动化的工作,比如批量替换,查找更改等,或者你想写一些界面程序,游戏等。

而对于专业的软件开发人员来说,通过C/C++/Java库去开发
、测试、编译等又太繁琐了。

这时候,Python是最佳的选择。

你可以写一些shell脚本或者bat脚本去移动文件或者修改数据,但不是很适合写界面程序或者游戏。C/C++/Java又太繁琐了。而Python比较适合快速的在各个平台(windows, Mac, Unix)完成你要的工作。

Python是一门真正的编程语言,它有高级的数据结构,比如可灵活操作的数组和字典。

Python是模块化的,它的标准库里面有你可用的一些模块,这些模块提供了比如文件I/O,sockets等功能。

Python可以写出比C/C++/Java更简洁的程序,原因有三:
1 有高级的数据结构
2 通过缩进进行区分声明块而不是括号
3 不需要变量或者参数声明

Python是可扩展的。你可以把Python解释器嵌入到C程序中。

使用Python解释器

运行python解释器

方式1:
Python解释器在linux下一般安装在/usr/local/bin/python目录下,切换到该目录下,输入以下命令可以运行python解释器

</>复制代码

  1. python

windows下一般安装在C:Python27目录下,win+r快捷键,然后输入一下cmd,打开dos界面,输入以下命令,设置环境变量:

</>复制代码

  1. set path=%path%;C:python27

则任意目录下,输入python命令即可打开python解释器
方式2:

</>复制代码

  1. python -c command [arg] ..

因为命令行可能有一些特殊字符或者空白,最好用单引号引起来。
退出python解释器:
Unix下在命令行界面输入快捷键:Control-D, Windows下输入Control-Z。
或者输入:

</>复制代码

  1. quit()

调用python模块(模块也就是python源文件):

</>复制代码

  1. python -m module [arg] ...

进入交互命令模式:

</>复制代码

  1. python -i ...

参数传递

命令行的参数会赋值给sys模块的argv变量。可以通过import sys访问参数。argv的长度至少有1。当没有参数的时候,sys.argv[0]是一个空串。当脚本的名字为"-",则sys.argv[0]是"-",当用了-c命令,则sys.argv[0]的值为"-c"。当用了-m,sys.argv[0]的值为模块的名字。-c和-m后面的参数,python解释器不会处理。

交互模式

多行模式前面是... 单行是>>>

</>复制代码

  1. >>> the_world_is_flat = 1
  2. >>> if the_world_is_flat:
  3. ... print "Be careful not to fall off!"
  4. ...

解释器和环境

设置代码编码

一般情况是不用设置的 默认为utf-8

</>复制代码

  1. #!/usr/bin/env python
  2. # -*- coding: cp-1252 -*-

Python介绍

开头标识注释,>>>和...开头标识python语句

</>复制代码

  1. >>>
  2. >>> #这是注释
  3. ... a = 1;#这是注释
  4. >>> print a
  5. 1

把python当做计算器

数字

</>复制代码

  1. >>> 2 + 2
  2. 4
  3. >>> 50 - 5*6
  4. 20
  5. >>> (50 - 5.0*6) / 4
  6. 5.0
  7. >>> 8 / 5.0
  8. 1.6

这里2是int 5.0是float,/的结果是什么类型是根据参与计算的两个数,如果有一个数是float则返回float类型。
//操作符是向下取数,小数位为0。

</>复制代码

  1. >>> 12//7.0
  2. 1.0
  3. >>>

%是求余
**是多次方

</>复制代码

  1. >>> 5**2
  2. 25
  3. >>>

声明变量n=12
如果使用一个未声明的变量会报错

</>复制代码

  1. >>> n
  2. Traceback (most recent call last):
  3. File "", line 1, in
  4. NameError: name "n" is not defined
  5. >>>

多项式计算,会自动进行数据类型的转换:int和float一起计算,int会自动转为float

交互模式下,最后一个打印的变量会赋值给_

</>复制代码

  1. >>> tax = 12.5 / 100
  2. >>> price = 100.50
  3. >>> price * tax
  4. 12.5625
  5. >>> price + _
  6. 113.0625
  7. >>> round(_, 2)
  8. 113.06

_是只读的,不能被赋值。

字符串

单引号或者双引号里表示字符串,用来转义
如果不想要转义:字符串前加一个r

</>复制代码

  1. >>> print "C:some
  2. ame" # here
  3. means newline!
  4. C:some
  5. ame
  6. >>> print r"C:some
  7. ame" # note the r before the quote
  8. C:some
  9. ame

多行字符串:三个"""或者"""

</>复制代码

  1. print """
  2. Usage: thingy [OPTIONS]
  3. -h Display this usage message
  4. -H hostname Hostname to connect to
  5. """

标识去掉换行,没有输出是这样的:

</>复制代码

  1. >>> print """
  2. ... aef
  3. ... asdf
  4. ... """
  5. aef
  6. asdf

字符串拼接:+ 字符串重复:*

</>复制代码

  1. >>> "un"*2 +" awef"
  2. "unun awef"
  3. >>>

自动拼接:

</>复制代码

  1. >>> "Py" "thon"
  2. "Python"

获取字符串的单个字符

</>复制代码

  1. >>> a = "python"
  2. >>> a[0]
  3. "p"

负数标识从尾部开始读取: -0等于0 最后一个字符是-1

</>复制代码

  1. >>> a = "python"
  2. >>> a[-1]
  3. "n"
  4. >>>

取区间:

</>复制代码

  1. >>> a = "python"
  2. >>> a[0:2]
  3. "py"
  4. >>> a[2:]
  5. "thon"
  6. >>> a[:4]
  7. "pyth"
  8. >>> a[-2:]
  9. "on"
  10. >>>

越界访问数组会报错:

</>复制代码

  1. >>> word[42] # the word only has 6 characters
  2. Traceback (most recent call last):
  3. File "", line 1, in
  4. IndexError: string index out of range

但是取不存在的区间不会报错:

</>复制代码

  1. >>> a[-2:45]
  2. "on"
  3. >>>

字符串无法被修改:

</>复制代码

  1. >>> word[0] = "J"
  2. ...
  3. TypeError: "str" object does not support item assignment
  4. >>> word[2:] = "py"
  5. ...
  6. TypeError: "str" object does not support item assignment
  7. unicode字符串

支持unicode字符串:字符串前加u

</>复制代码

  1. >>> u"Hello World !"
  2. u"Hello World !"
  3. >>> u"Hellou0020World !"
  4. u"Hello World !"

0x0020标识空格
支持原始模式: 字符串前面加入ur
python的默认编码方式是:ASCII码,如果Unicode字符串被打印或者写到文件或者是str()方法转化都会默认转为ASCII码,如果字符串不在0-127范围就会报错

</>复制代码

  1. >>> u"abc"
  2. u"abc"
  3. >>> str(u"abc")
  4. "abc"
  5. >>> u"äöü"
  6. u"xe4xf6xfc"
  7. >>> str(u"äöü")
  8. Traceback (most recent call last):
  9. File "", line 1, in ?
  10. UnicodeEncodeError: "ascii" codec can"t encode characters in position 0-2: ordinal not in range(128)

转换为特定编码:方法的参数为小写

</>复制代码

  1. >>> u"äöü".encode("utf-8")
  2. "xc3xa4xc3xb6xc3xbc"
数组

定义一个数组

</>复制代码

  1. >>> squares = [1, 4, 9, 16, 25]
  2. >>> squares
  3. [1, 4, 9, 16, 25]

获取数组内元素

</>复制代码

  1. >>> squares[0] # indexing returns the item
  2. 1
  3. >>> squares[-1]
  4. 25
  5. >>> squares[-3:] # slicing returns a new list 例子三
  6. [9, 16, 25]

获取数组内片段,比如上面例子三,会返回一个新的数组拷贝,原数组不会发生改变
数组合并:

</>复制代码

  1. >>> squares + [36, 49, 64, 81, 100]
  2. [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

字符串的内容是不能被更改的,而数组是可以被更改的:

</>复制代码

  1. >>> cubes = [1, 8, 27, 65, 125] # something"s wrong here
  2. >>> 4 ** 3 # the cube of 4 is 64, not 65!
  3. 64
  4. >>> cubes[3] = 64 # replace the wrong value
  5. >>> cubes
  6. [1, 8, 27, 64, 125]

给数组添加元素:

</>复制代码

  1. >>> cubes.append(216) # add the cube of 6
  2. >>> cubes.append(7 ** 3) # and the cube of 7
  3. >>> cubes
  4. [1, 8, 27, 64, 125, 216, 343]

可以赋值给截取的数组:

</>复制代码

  1. >>> letters = ["a", "b", "c", "d", "e", "f", "g"]
  2. >>> letters
  3. ["a", "b", "c", "d", "e", "f", "g"]
  4. >>> # replace some values
  5. >>> letters[2:5] = ["C", "D", "E"]
  6. >>> letters
  7. ["a", "b", "C", "D", "E", "f", "g"]
  8. >>> # now remove them
  9. >>> letters[2:5] = []
  10. >>> letters
  11. ["a", "b", "f", "g"]
  12. >>> # clear the list by replacing all the elements with an empty list
  13. >>> letters[:] = []
  14. >>> letters
  15. []

获取数组的长度:

</>复制代码

  1. >>> letters = ["a", "b", "c", "d"]
  2. >>> len(letters)
  3. 4

数组的元素也可以是一个数组:

</>复制代码

  1. >>> a = ["a", "b", "c"]
  2. >>> n = [1, 2, 3]
  3. >>> x = [a, n]
  4. >>> x
  5. [["a", "b", "c"], [1, 2, 3]]
  6. >>> x[0]
  7. ["a", "b", "c"]
  8. >>> x[0][1]
  9. "b"

终于开始编程了!

如何实现一个斐波那契:

</>复制代码

  1. >>> # 这是一个注释
  2. ... a, b = 0, 1 #分别给a赋值为0 b赋值为1
  3. >>> while b < 10:#这是一个循环
  4. ... print b #打印b的值(并且这里的代码前面有空格(也就是行缩进))
  5. ... a, b = b, a+b #a赋值为b,b赋值为a+b的和
  6. ...
  7. 1
  8. 1
  9. 2
  10. 3
  11. 5
  12. 8

之前说过,行缩进标识接下来是一个代码块。
print方法,可以控制格式,比如增加空格:

</>复制代码

  1. >>> i = 256*256
  2. >>> print "The value of i is", i
  3. The value of i is 65536

在print语句最后加一个逗号,避免打印结果换行:

</>复制代码

  1. >>> a, b = 0, 1
  2. >>> while b < 1000:
  3. ... print b,
  4. ... a, b = b, a+b
  5. ...
  6. 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987

控制流

if语句

</>复制代码

  1. >>> x = int(raw_input("Please enter an integer: "))
  2. Please enter an integer: 42
  3. >>> if x < 0: #冒号可以开启多行模式
  4. ... x = 0
  5. ... print "Negative changed to zero"
  6. ... elif x == 0:
  7. ... print "Zero"
  8. ... elif x == 1:
  9. ... print "Single"
  10. ... else:
  11. ... print "More"
  12. ...

if…elif..else(不是必须的)…

for

Python的for可以遍历数组和字符串(这个和C语言的for语句有略微不同)

</>复制代码

  1. >>> # Measure some strings:
  2. ... words = ["cat", "window", "defenestrate"]
  3. >>> for w in words:
  4. ... print w, len(w)
  5. ...
  6. cat 3
  7. window 6
  8. defenestrate 12

在循环内修改一个数组:首先通过截取数组的方法对原数组进行拷贝(这个知识点之前有提过)

</>复制代码

  1. >>> for w in words[:]: # words[:]可以对原数组进行拷贝
  2. ... if len(w) > 6:
  3. ... words.insert(0, w)
  4. ...
  5. >>> words
  6. ["defenestrate", "cat", "window", "defenestrate"]
  7. range()函数

range函数能根据算法创建一个数组

</>复制代码

  1. >>> range(5, 10) #创建所有元素为5到10区间并递增的数组
  2. [5, 6, 7, 8, 9]
  3. >>> range(0, 10, 3)#递增3
  4. [0, 3, 6, 9]
  5. >>> range(-10, -100, -30)#递减30
  6. [-10, -40, -70]

遍历数组的索引:

</>复制代码

  1. >>> a = ["Mary", "had", "a", "little", "lamb"]
  2. >>> for i in range(len(a)):
  3. ... print i, a[i]
  4. ...
  5. 0 Mary
  6. 1 had
  7. 2 a
  8. 3 little
  9. 4 lamb

退出循环

break语句执行会退出里层的for循环;continue会跳过后面语句的执行(和C语言用法一样)。

</>复制代码

  1. >>> for n in range(2, 10):
  2. ... for x in range(2, n):
  3. ... if n % x == 0:
  4. ... print n, "equals", x, "*", n/x
  5. ... break
  6. ... else:
  7. ... # loop fell through without finding a factor
  8. ... print n, "is a prime number"
  9. ...
  10. 2 is a prime number
  11. 3 is a prime number
  12. 4 equals 2 * 2
  13. 5 is a prime number
  14. 6 equals 2 * 3
  15. 7 is a prime number
  16. 8 equals 2 * 4
  17. 9 equals 3 * 3

pass语句

pass语句不会做任何事,只是用来占位用的

</>复制代码

  1. >>> class MyEmptyClass:
  2. ... pass
  3. ...
  4. >>> def initlog(*args):
  5. ... pass # Remember to implement this!
  6. ...

定义函数和调用函数

</>复制代码

  1. >>> def fib(n): # def关键字标识定义函数,这里函数名为fib
  2. ... """Print a Fibonacci series up to n.""" #
  3. ... a, b = 0, 1
  4. ... while a < n:
  5. ... print a,
  6. ... a, b = b, a+b
  7. ...
  8. >>> # Now call the function we just defined:
  9. ... fib(2000)
  10. 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597

注意函数体要代码要缩进
函数可以被赋值(fib会被加入符号表):

</>复制代码

  1. >>> fib
  2. >>> f = fib # f也会被加入符号表
  3. >>> f(100)
  4. 0 1 1 2 3 5 8 13 21 34 55 89

即便函数没有return,也会返回一个None

</>复制代码

  1. >>> fib(0)
  2. >>> print fib(0)
  3. None

return后面没有跟任何东西也是返回None

</>复制代码

  1. >>> def fib2(n): # return Fibonacci series up to n
  2. ... result = []
  3. ... a, b = 0, 1
  4. ... while a < n:
  5. ... result.append(a) # 这里是调用数组的append方法
  6. ... a, b = b, a+b
  7. ... return result
  8. ...
  9. >>> f100 = fib2(100) # call it
  10. >>> f100 # write the result
  11. [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]

定义带参数的函数

参数带默认值:retries的默认值为4

</>复制代码

  1. def ask_ok(prompt, retries=4, complaint="Yes or no, please!"):
  2. while True: # True是关键字
  3. ok = raw_input(prompt) #raw_input是内置的函数,用于IO输入
  4. if ok in ("y", "ye", "yes"):
  5. return True
  6. if ok in ("n", "no", "nop", "nope"):
  7. return False
  8. retries = retries - 1
  9. if retries < 0:
  10. raise IOError("refusenik user") # raise是关键字 抛出异常
  11. print complaint

默认值可以为变量:i是一个变量

</>复制代码

  1. i = 5
  2. def f(arg=i):
  3. print arg
  4. i = 6
  5. f()

默认参数如果是一个可变的对象,会被赋值多次:

</>复制代码

  1. def f(a, L=[]):
  2. L.append(a)
  3. return L
  4. print f(1)
  5. print f(2)
  6. print f(3)
  7. 会打印出:
  8. [1]
  9. [1, 2]
  10. [1, 2, 3]

如果你不想L被改变,你可以这么做:

</>复制代码

  1. def f(a, L=None):
  2. if L is None:
  3. L = []
  4. L.append(a)
  5. return L

如果只接受一个参数,但是传递了两个参数会报错:

</>复制代码

  1. >>> def function(a):
  2. ... pass
  3. ...
  4. >>> function(0, a=0)
  5. Traceback (most recent call last):
  6. File "", line 1, in
  7. TypeError: function() got multiple values for keyword argument "a"
  8. **kewords接收字典参数:
  9. def cheeseshop(kind, *arguments, **keywords):
  10. print "-- Do you have any", kind, "?"
  11. print "-- I"m sorry, we"re all out of", kind
  12. for arg in arguments:
  13. print arg
  14. print "-" * 40
  15. keys = sorted(keywords.keys()) #按字典顺序
  16. for kw in keys:
  17. print kw, ":", keywords[kw]

*arg接受不确定个数的参数:

</>复制代码

  1. def write_multiple_items(file, separator, *args):
  2. file.write(separator.join(args))

自动解析参数:

</>复制代码

  1. >>> range(3, 6) # 正常情况调用方式
  2. [3, 4, 5]
  3. >>> args = [3, 6]
  4. >>> range(*args) # 从一个数组里解析参数
  5. [3, 4, 5]
  6. >>> def parrot(voltage, state="a stiff", action="voom"):
  7. ... print "-- This parrot wouldn"t", action,
  8. ... print "if you put", voltage, "volts through it.",
  9. ... print "E"s", state, "!"
  10. ...
  11. >>> d = {"voltage": "four million", "state": "bleedin" demised", "action": "VOOM"}
  12. >>> parrot(**d)
  13. -- This parrot wouldn"t VOOM if you put four million volts through it. E"s bleedin" demised !

文档字符串:

</>复制代码

  1. >>> def my_function():
  2. ... """Do nothing, but document it.
  3. ...
  4. ... No, really, it doesn"t do anything.
  5. ... """
  6. ... pass
  7. ...
  8. >>> print my_function.__doc__
  9. Do nothing, but document it.
  10. No, really, it doesn"t do anything.

Lambda表达式一个匿名函数,lambda a, b: a+b. a和b是两个参数,结果返回a和b的和:

</>复制代码

  1. >>> def make_incrementor(n):
  2. ... return lambda x: x + n
  3. ...
  4. >>> f = make_incrementor(42)
  5. >>> f(0)
  6. 42
  7. >>> f(1)
  8. 43

lambda也可以作为参数传递:

</>复制代码

  1. >>> pairs = [(1, "one"), (2, "two"), (3, "three"), (4, "four")]
  2. >>> pairs.sort(key=lambda pair: pair[1])
  3. >>> pairs
  4. [(4, "four"), (1, "one"), (3, "three"), (2, "two")]
编码格式建议

不用Tab缩进,用4倍空格缩进
必要时换行(避免单行超出79个字符)
用空格区分函数或者类或者函数内部的一大段代码
代码前面加上必要的注释
用文档字符串
操作符liagn两边或者逗号后面必须空格
函数采用lower_case_width_underscore方式命令,类用驼峰(CanekCase)方式命名;总是用self当作类的第一个方法的参数
不要用特殊的编码格式(ASCII是兼容所有的)

数据结构 数组

python数据默认有一些常用方法:比如append, extend, insert等等

作为堆栈使用

</>复制代码

  1. >>> stack = [3, 4, 5]
  2. >>> stack.append(6)
  3. >>> stack.append(7)
  4. >>> stack
  5. [3, 4, 5, 6, 7]
  6. >>> stack.pop()
  7. 7
  8. >>> stack
  9. [3, 4, 5, 6]
  10. >>> stack.pop()
  11. 6
  12. >>> stack.pop()
  13. 5
  14. >>> stack
  15. [3, 4]
作为队列使用

</>复制代码

  1. >>> from collections import deque
  2. >>> queue = deque(["Eric", "John", "Michael"])
  3. >>> queue.append("Terry") # Terry arrives
  4. >>> queue.append("Graham") # Graham arrives
  5. >>> queue.popleft() # The first to arrive now leaves
  6. "Eric"
  7. >>> queue.popleft() # The second to arrive now leaves
  8. "John"
  9. >>> queue # Remaining queue in order of arrival
  10. deque(["Michael", "Terry", "Graham"])
一些常用的方法

filter(function, sequence) : 返回function的值为true的所有值

</>复制代码

  1. >>> def f(x): return x % 3 == 0 or x % 5 == 0
  2. ...
  3. >>> filter(f, range(2, 25))
  4. [3, 5, 6, 9, 10, 12, 15, 18, 20, 21, 24]

map(function, sequence): 返回处理后的值

</>复制代码

  1. >>> def cube(x): return x*x*x
  2. ...
  3. >>> map(cube, range(1, 11))
  4. [1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]

传递两个数组: 分别从一个数组里取出一个数 返回相加后的结果

</>复制代码

  1. >>> seq = range(8)
  2. >>> def add(x, y): return x+y
  3. ...
  4. >>> map(add, seq, seq)
  5. [0, 2, 4, 6, 8, 10, 12, 14]

reduce(function, sequence) :把数组的第一个和第二个参数想加的和和第三个数再加。。如果数组为空,会返回异常

</>复制代码

  1. >>> def add(x,y): return x+y
  2. ...
  3. >>> reduce(add, range(1, 11))
  4. 55

reduce可以指定开始的第一个数的索引:

</>复制代码

  1. >>> def sum(seq):
  2. ... def add(x,y): return x+y
  3. ... return reduce(add, seq, 0)
  4. ...
  5. >>> sum(range(1, 11))
  6. 55
  7. >>> sum([])
  8. 0

创建数组的几种形式:

</>复制代码

  1. >>> squares = []
  2. >>> for x in range(10):
  3. ... squares.append(x**2)
  4. ...
  5. >>> squares
  6. [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

</>复制代码

  1. squares = [x**2 for x in range(10)]

</>复制代码

  1. squares = map(lambda x: x**2, range(10))

更复杂点的例子:x,y作为一个整体 必须加上括号

</>复制代码

  1. >>> [(x, y) for x in [1,2,3] for y in [3,1,4] if x != y]
  2. [(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]

更多例子:

</>复制代码

  1. >>> freshfruit = [" banana", " loganberry ", "passion fruit "]
  2. >>> [weapon.strip() for weapon in freshfruit]
  3. ["banana", "loganberry", "passion fruit"]
  4. >>> [x, x**2 for x in range(6)]
  5. File "", line 1, in
  6. [x, x**2 for x in range(6)]
  7. ^
  8. SyntaxError: invalid syntax
  9. >>> # flatten a list using a listcomp with two "for"
  10. >>> vec = [[1,2,3], [4,5,6], [7,8,9]]
  11. >>> [num for elem in vec for num in elem]
  12. [1, 2, 3, 4, 5, 6, 7, 8, 9]
  13. >>> from math import pi
  14. >>> [str(round(pi, i)) for i in range(1, 6)]
  15. ["3.1", "3.14", "3.142", "3.1416", "3.14159"]
二维数组

</>复制代码

  1. >>> matrix = [
  2. ... [1, 2, 3, 4],
  3. ... [5, 6, 7, 8],
  4. ... [9, 10, 11, 12],
  5. ... ]

复杂点的例子:

</>复制代码

  1. >>> [[row[i] for row in matrix] for i in range(4)]
  2. [[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]

相当于:

</>复制代码

  1. >>> transposed = []
  2. >>> for i in range(4):
  3. ... transposed.append([row[i] for row in matrix])
  4. ...
  5. >>> transposed
  6. [[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]

删除数组内元素:del

</>复制代码

  1. >>> a = [-1, 1, 66.25, 333, 333, 1234.5]
  2. >>> del a[0]
  3. >>> a
  4. [1, 66.25, 333, 333, 1234.5]
  5. >>> del a[2:4]
  6. >>> a
  7. [1, 66.25, 1234.5]
  8. >>> del a[:]
  9. >>> a
  10. []

删除整个数组:

</>复制代码

  1. >>> del a
新类型:元组。

输入可以加括号,也可以不加。输出都是带括号的。

</>复制代码

  1. >>> t = 12345, 54321, "hello!" # 输入 没加括号
  2. >>> t[0]
  3. 12345
  4. >>> t
  5. (12345, 54321, "hello!") # 输出 带括号
  6. >>> # Tuples may be nested:
  7. ... u = t, (1, 2, 3, 4, 5)
  8. >>> u
  9. ((12345, 54321, "hello!"), (1, 2, 3, 4, 5))
  10. >>> # 无法被修改
  11. ... t[0] = 88888
  12. Traceback (most recent call last):
  13. File "", line 1, in
  14. TypeError: "tuple" object does not support item assignment
  15. >>> # 内部的元素可以是可变的类型 比如数组等
  16. ... v = ([1, 2, 3], [3, 2, 1])
  17. >>> v
  18. ([1, 2, 3], [3, 2, 1])

空元组和只有一个元素的元组:

</>复制代码

  1. >>> empty = ()
  2. >>> singleton = "hello", # <-- note trailing comma
  3. >>> len(empty)
  4. 0
  5. >>> len(singleton)
  6. 1
  7. >>> singleton
  8. ("hello",)

逆序元素:

</>复制代码

  1. >>> t = (12345, 54321, "hello!")
  2. >>> x, y, z = t
新的类型:集合

创建空集合:set()

</>复制代码

  1. >>> basket = ["apple", "orange", "apple", "pear", "orange", "banana"]
  2. >>> fruit = set(basket) # 创建集合
  3. >>> fruit
  4. set(["orange", "pear", "apple", "banana"])
  5. >>> "orange" in fruit # 测试是否oranage是否是集合fruit内部
  6. True
  7. >>> "crabgrass" in fruit
  8. False

集合a, b 之间的交集 并集

</>复制代码

  1. >>> a = set("abracadabra")
  2. >>> b = set("alacazam")
  3. >>> a # unique letters in a
  4. set(["a", "r", "b", "c", "d"])
  5. >>> a - b # letters in a but not in b
  6. set(["r", "d", "b"])
  7. >>> a | b # letters in either a or b
  8. set(["a", "c", "r", "d", "b", "m", "z", "l"])
  9. >>> a & b # letters in both a and b
  10. set(["a", "c"])
  11. >>> a ^ b # letters in a or b but not both
  12. set(["r", "d", "b", "m", "z", "l"])

</>复制代码

  1. >>> a = {x for x in "abracadabra" if x not in "abc"}
  2. >>> a
  3. set(["r", "d"])
新的类型:字典

字典是根据key索引的,而key数据类型可以为数字或者字符串,元组的元素都是不可变的,也可以作为key。数组不能作为key,因为数组可被修改

</>复制代码

  1. >>> tel = {"jack": 4098, "sape": 4139}
  2. >>> tel["guido"] = 4127
  3. >>> tel
  4. {"sape": 4139, "guido": 4127, "jack": 4098}
  5. >>> tel["jack"]
  6. 4098
  7. >>> del tel["sape"]
  8. >>> tel["irv"] = 4127
  9. >>> tel
  10. {"guido": 4127, "irv": 4127, "jack": 4098}
  11. >>> tel.keys()
  12. ["guido", "irv", "jack"]
  13. >>> "guido" in tel
  14. True

dict方法直接创建字典:

</>复制代码

  1. >>> dict([("sape", 4139), ("guido", 4127), ("jack", 4098)])
  2. {"sape": 4139, "jack": 4098, "guido": 4127}

</>复制代码

  1. >>> {x: x**2 for x in (2, 4, 6)}
  2. {2: 4, 4: 16, 6: 36}

</>复制代码

  1. >>> dict(sape=4139, guido=4127, jack=4098)
  2. {"sape": 4139, "jack": 4098, "guido": 4127}
遍历

通过enumerate方法

</>复制代码

  1. >>> for i, v in enumerate(["tic", "tac", "toe"]):
  2. ... print i, v
  3. ...
  4. 0 tic
  5. 1 tac
  6. 2 toe

一次性遍历多个(这个特性不错。。

</>复制代码

  1. >>> questions = ["name", "quest", "favorite color"]
  2. >>> answers = ["lancelot", "the holy grail", "blue"]
  3. >>> for q, a in zip(questions, answers):
  4. ... print "What is your {0}? It is {1}.".format(q, a)
  5. ...
  6. What is your name? It is lancelot.
  7. What is your quest? It is the holy grail.
  8. What is your favorite color? It is blue

逆序遍历:reversed

</>复制代码

  1. >>> for i in reversed(xrange(1,10,2)):
  2. ... print i
  3. ...
  4. 9
  5. 7
  6. 5
  7. 3
  8. 1

对数组排序(sorted方法),然后遍历:

</>复制代码

  1. >>> basket = ["apple", "orange", "apple", "pear", "orange", "banana"]
  2. >>> for f in sorted(set(basket)):
  3. ... print f
  4. ...
  5. apple
  6. banana
  7. orange
  8. pear

遍历字典的时候,获得key和value:

</>复制代码

  1. >>> knights = {"gallahad": "the pure", "robin": "the brave"}
  2. >>> for k, v in knights.iteritems():
  3. ... print k, v
  4. ...
  5. gallahad the pure
  6. robin the brave

遍历的时候改变一个数组:

</>复制代码

  1. >>> import math
  2. >>> raw_data = [56.2, float("NaN"), 51.7, 55.3, 52.5, float("NaN"), 47.8]
  3. >>> filtered_data = []
  4. >>> for value in raw_data:
  5. ... if not math.isnan(value):
  6. ... filtered_data.append(value)
  7. ...
  8. >>> filtered_data
  9. [56.2, 51.7, 55.3, 52.5, 47.8]
更多条件语句

比较运算符:
in和not in判断是否在序列里面; is和is not用来比较两个对象是否是同一个对象;
比较可以链式: a < b == c 判断a小于b,并且b等于c
布尔操作符:and和or 优先级比比较运算符低 not优先级最高 or最低

布尔运算符,当一个满足条件不会继续下面的计算

比较结果可以被赋值:

</>复制代码

  1. >>> string1, string2, string3 = "", "Trondheim", "Hammer Dance"
  2. >>> non_null = string1 or string2 or string3
  3. >>> non_null
  4. "Trondheim"
模块

退出解释器后,所有声明的函数或者变量都不存在了。所以我们需要创建一个python脚本,可持续地运行。每一个脚本文件称之为一个模块。
比如我们创建一个文件:fibo.py

</>复制代码

  1. # 这是一个模块
  2. def fib(n): # 定义函数fib
  3. a, b = 0, 1
  4. while b < n:
  5. print b,
  6. a, b = b, a+b
  7. def fib2(n): # 定义函数fib2
  8. result = []
  9. a, b = 0, 1
  10. while b < n:
  11. result.append(b)
  12. a, b = b, a+b
  13. return result

在解释器里面导入这个模块:

</>复制代码

  1. >>> import fibo

访问模块的函数:

</>复制代码

  1. >>> fibo.fib(1000)
  2. 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987
  3. >>> fibo.fib2(100)
  4. [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
  5. >>> fibo.__name__
  6. "fibo"

函数赋给一个变量

</>复制代码

  1. >>> fib = fibo.fib
  2. >>> fib(500)
  3. 1 1 2 3 5 8 13 21 34 55 89 144 233 377
执行模块脚本

这样运行一个模块

</>复制代码

  1. python fibo.py

和导入一个模块,并且把__name__设置为__main__是一样的:相当于把下面的代码放到模块的底部

</>复制代码

  1. if __name__ == "__main__":
  2. import sys
  3. fib(int(sys.argv[1]))

这样单纯导入是不会运行这个脚本的:

</>复制代码

  1. >>> import fibo
  2. >>>
模块寻找路径

1 内置模块
2 搜索sys.path里面的所有目录

sys.path初始化的内容:
当前目录
PYTHONPATH (目录路径,它和环境变量的PATH语法一致)
Python安装路径

sys.path会被修改,当前目录优先于标准库路径。

编译后的Python文件

如果 spam.pyc(编译后的Python文件)和spam.py共存,会优先用编译后的文件。spam.pyc保存的编译时间和spam.py的修改时间不一致,则编译后的文件会被忽略(也就是用spam.py文件)。spam.pyc文件是平台独立的,也就是说能被各个平台共享。

标准模块

Python有自己的标准库。为了达到更底层的东西,有些模块已经内置到解析器中。而且有些内置模块依赖于环境,比如winreg模块只在window环境下提供。而一个值得关注的模块是:sys,它被内置到了每个Python解释器中。sys.ps1和sys.ps2表示Python的提示符

</>复制代码

  1. >>>import sys
  2. >>>sys.ps1
  3. ">>> "
  4. >>> sys.ps2
  5. "... "
  6. >>> sys.ps1 = "C> "
  7. C> print "Yuck!"
  8. Yuck!
  9. C>

sys.path的值是解释器的模块搜索路径。我们可以增加路径:

</>复制代码

  1. >>> import sys
  2. >>> sys.path.append("/ufs/guido/lib/python")
dir()函数

dir()函数返回一个字符串的数组,它被用来表示一个模块定义了哪些名字

</>复制代码

  1. >>> import fibo, sys
  2. >>> dir(fibo)
  3. ["__name__", "fib", "fib2"]
  4. >>> dir(sys)
  5. ["__displayhook__", "__doc__", "__excepthook__", "__name__", "__package__",
  6. "__stderr__", "__stdin__", "__stdout__", "_clear_type_cache",
  7. "_current_frames", "_getframe", "_mercurial", "api_version", "argv",
  8. "builtin_module_names", "byteorder", "call_tracing", "callstats",
  9. "copyright", "displayhook", "dont_write_bytecode", "exc_clear", "exc_info",
  10. "exc_traceback", "exc_type", "exc_value", "excepthook", "exec_prefix",
  11. "executable", "exit", "flags", "float_info", "float_repr_style",
  12. "getcheckinterval", "getdefaultencoding", "getdlopenflags",
  13. "getfilesystemencoding", "getobjects", "getprofile", "getrecursionlimit",
  14. "getrefcount", "getsizeof", "gettotalrefcount", "gettrace", "hexversion",
  15. "long_info", "maxint", "maxsize", "maxunicode", "meta_path", "modules",
  16. "path", "path_hooks", "path_importer_cache", "platform", "prefix", "ps1",
  17. "py3kwarning", "setcheckinterval", "setdlopenflags", "setprofile",
  18. "setrecursionlimit", "settrace", "stderr", "stdin", "stdout", "subversion",
  19. "version", "version_info", "warnoptions"]

不带参数则返回当前你定义的模块函数变量名字

</>复制代码

  1. >>> a = [1, 2, 3, 4, 5]
  2. >>> import fibo
  3. >>> fib = fibo.fib
  4. >>> dir()
  5. ["__builtins__", "__name__", "__package__", "a", "fib", "fibo", "sys"]

dir()不会返回内置的函数和变量。如果要打印内置的话,需要传递__builtin__

</>复制代码

  1. >>> import __builtin__
  2. >>> dir(__builtin__)
  3. ["ArithmeticError", "AssertionError", "AttributeError", "BaseException",
  4. "BufferError", "BytesWarning", "DeprecationWarning", "EOFError",
  5. "Ellipsis", "EnvironmentError", "Exception", "False", "FloatingPointError",
  6. "FutureWarning", "GeneratorExit", "IOError", "ImportError", "ImportWarning",
  7. "IndentationError", "IndexError", "KeyError", "KeyboardInterrupt",
  8. "LookupError", "MemoryError", "NameError", "None", "NotImplemented",
  9. "NotImplementedError", "OSError", "OverflowError",
  10. "PendingDeprecationWarning", "ReferenceError", "RuntimeError",
  11. "RuntimeWarning", "StandardError", "StopIteration", "SyntaxError",
  12. "SyntaxWarning", "SystemError", "SystemExit", "TabError", "True",
  13. "TypeError", "UnboundLocalError", "UnicodeDecodeError",
  14. "UnicodeEncodeError", "UnicodeError", "UnicodeTranslateError",
  15. "UnicodeWarning", "UserWarning", "ValueError", "Warning",
  16. "ZeroDivisionError", "_", "__debug__", "__doc__", "__import__",
  17. "__name__", "__package__", "abs", "all", "any", "apply", "basestring",
  18. "bin", "bool", "buffer", "bytearray", "bytes", "callable", "chr",
  19. "classmethod", "cmp", "coerce", "compile", "complex", "copyright",
  20. "credits", "delattr", "dict", "dir", "divmod", "enumerate", "eval",
  21. "execfile", "exit", "file", "filter", "float", "format", "frozenset",
  22. "getattr", "globals", "hasattr", "hash", "help", "hex", "id", "input",
  23. "int", "intern", "isinstance", "issubclass", "iter", "len", "license",
  24. "list", "locals", "long", "map", "max", "memoryview", "min", "next",
  25. "object", "oct", "open", "ord", "pow", "print", "property", "quit",
  26. "range", "raw_input", "reduce", "reload", "repr", "reversed", "round",
  27. "set", "setattr", "slice", "sorted", "staticmethod", "str", "sum", "super",
  28. "tuple", "type", "unichr", "unicode", "vars", "xrange", "zip"]

包是组织Python模块的一种方式,比如A.B 标识包A下有一个子模块B。
一个包的结构类似如下:

</>复制代码

  1. sound/ Top-level package
  2. __init__.py Initialize the sound package
  3. formats/ Subpackage for file format conversions
  4. __init__.py
  5. wavread.py
  6. wavwrite.py
  7. aiffread.py
  8. aiffwrite.py
  9. auread.py
  10. auwrite.py
  11. ...
  12. effects/ Subpackage for sound effects
  13. __init__.py
  14. echo.py
  15. surround.py
  16. reverse.py
  17. ...
  18. filters/ Subpackage for filters
  19. __init__.py
  20. equalizer.py
  21. vocoder.py
  22. karaoke.py
  23. ...

那么我们怎么导入它:

</>复制代码

  1. import sound.effects.echo

然后怎么引用: 必须用全名引用

</>复制代码

  1. sound.effects.echo.echofilter(input, output, delay=0.7, atten=4)

另外一种引用的方式是:

</>复制代码

  1. from sound.effects import echo

这种方式引入,可以避免全名

</>复制代码

  1. echo.echofilter(input, output, delay=0.7, atten=4)

当然,你也可以引入函数或者变量:

</>复制代码

  1. from sound.effects.echo import echofilter

直接调用函数:

</>复制代码

  1. echofilter(input, output, delay=0.7, atten=4)

注意:以下方式导入,最后一个(subsubitem)必须是包

</>复制代码

  1. import item.subitem.subsubitem
导入包

在sound/effects/__init__.py 这个里面定义:

</>复制代码

  1. __all__ = ["echo", "surround", "reverse"]

那么:通过以下方式会导入上面all指定的模块

</>复制代码

  1. from sound.effects import *

如果all没定义,那么import导入的情况是不一定的。

</>复制代码

  1. import sound.effects.echo
  2. import sound.effects.surround
  3. from sound.effects import *

比如上面这种写法,会导入echo和surround

不推荐使用*。

内部包引用

可以使用相对导入:

</>复制代码

  1. from . import echo
  2. from .. import formats
  3. from ..filters import equalizer
输入和输出 输出格式

输出方法:sys.stdout标准输出, print write()方法等
格式输出: str.format()
转为字符串用repr()和str()函数 :

</>复制代码

  1. >>> s = "Hello, world."
  2. >>> str(s)
  3. "Hello, world."
  4. >>> repr(s)
  5. ""Hello, world.""
  6. >>> str(1.0/7.0)
  7. "0.142857142857"
  8. >>> repr(1.0/7.0)
  9. "0.14285714285714285"
  10. >>> x = 10 * 3.25
  11. >>> y = 200 * 200
  12. >>> s = "The value of x is " + repr(x) + ", and y is " + repr(y) + "..."
  13. >>> print s
  14. The value of x is 32.5, and y is 40000...
  15. >>> # The repr() of a string adds string quotes and backslashes:
  16. ... hello = "hello, world
  17. "
  18. >>> hellos = repr(hello)
  19. >>> print hellos
  20. "hello, world
  21. "
  22. >>> # The argument to repr() may be any Python object:
  23. ... repr((x, y, ("spam", "eggs")))
  24. "(32.5, 40000, ("spam", "eggs"))"

打印表格形式:

</>复制代码

  1. >>> for x in range(1, 11):
  2. ... print repr(x).rjust(2), repr(x*x).rjust(3),
  3. ... # Note trailing comma on previous line
  4. ... print repr(x*x*x).rjust(4)
  5. ...
  6. 1 1 1
  7. 2 4 8
  8. 3 9 27
  9. 4 16 64
  10. 5 25 125
  11. 6 36 216
  12. 7 49 343
  13. 8 64 512
  14. 9 81 729
  15. 10 100 1000
  16. >>> for x in range(1,11):
  17. ... print "{0:2d} {1:3d} {2:4d}".format(x, x*x, x*x*x)
  18. ...
  19. 1 1 1
  20. 2 4 8
  21. 3 9 27
  22. 4 16 64
  23. 5 25 125
  24. 6 36 216
  25. 7 49 343
  26. 8 64 512
  27. 9 81 729
  28. 10 100 1000

str.rjust() 对字符串右对齐
str.zfill() 字符串保证位数

</>复制代码

  1. >>> "12".zfill(5)
  2. "00012"
  3. >>> "-3.14".zfill(7)
  4. "-003.14"
  5. >>> "3.14159265359".zfill(5)
  6. "3.14159265359"

str.format()的基本使用:

</>复制代码

  1. >>> print "We are the {} who say "{}!"".format("knights", "Ni")
  2. We are the knights who say "Ni!"

交换位置:

</>复制代码

  1. >>> print "{0} and {1}".format("spam", "eggs")
  2. spam and eggs
  3. >>> print "{1} and {0}".format("spam", "eggs")
  4. eggs and spam

通过key访问:

</>复制代码

  1. >>> print "This {food} is {adjective}.".format(
  2. ... food="spam", adjective="absolutely horrible")
  3. This spam is absolutely horrible.

混合使用:

</>复制代码

  1. >>> print "The story of {0}, {1}, and {other}.".format("Bill", "Manfred",
  2. ... other="Georg")
  3. The story of Bill, Manfred, and Georg.

"!s" (调用str()) and "!r" (调用repr()) 打印前进行格式转换:

</>复制代码

  1. >>> import math
  2. >>> print "The value of PI is approximately {}.".format(math.pi)
  3. The value of PI is approximately 3.14159265359.
  4. >>> print "The value of PI is approximately {!r}.".format(math.pi)
  5. The value of PI is approximately 3.141592653589793.

":" 可控制小数点:

</>复制代码

  1. >>> import math
  2. >>> print "The value of PI is approximately {0:.3f}.".format(math.pi)
  3. The value of PI is approximately 3.142.

控制表格:

</>复制代码

  1. >>> table = {"Sjoerd": 4127, "Jack": 4098, "Dcab": 7678}
  2. >>> for name, phone in table.items():
  3. ... print "{0:10} ==> {1:10d}".format(name, phone)
  4. ...
  5. Jack ==> 4098
  6. Dcab ==> 7678
  7. Sjoerd ==> 4127

通过[]访问key:

</>复制代码

  1. >>> table = {"Sjoerd": 4127, "Jack": 4098, "Dcab": 8637678}
  2. >>> print ("Jack: {0[Jack]:d}; Sjoerd: {0[Sjoerd]:d}; "
  3. ... "Dcab: {0[Dcab]:d}".format(table))
  4. Jack: 4098; Sjoerd: 4127; Dcab: 8637678
% 操作符也可以格式化(老式的)

</>复制代码

  1. >>> import math
  2. >>> print "The value of PI is approximately %5.3f." % math.pi
  3. The value of PI is approximately 3.142.
读写文件

open()打开文件:open(filename, mode)

</>复制代码

  1. >>> f = open("workfile", "w")
  2. >>> print f
  3. ‘b’标识二进制形式,跨平台

  4. 文件对象的方法
  5. 读文件:f.read(size)

  6. </>复制代码

    1. >>> f.read()
    2. "This is the entire file.
    3. "
    4. >>> f.read()
    5. ""
  7. 带换行:

  8. </>复制代码

    1. >>> f.readline()
    2. "This is the first line of the file.
    3. "
    4. >>> f.readline()
    5. "Second line of the file
    6. "
    7. >>> f.readline()
    8. ""
  9. 读取一个文件的所有行:

  10. </>复制代码

    1. >> for line in f:
    2. print line,
    3. This is the first line of the file.
    4. Second line of the file
  11. 或者list(f) or f.readlines()
    字符串写入文件:

  12. </>复制代码

    1. >>> f.write("This is a test
    2. ")
  13. 将其他类型写入文件需先转为字符串:

  14. </>复制代码

    1. >>> value = ("the answer", 42)
    2. >>> s = str(value)
    3. >>> f.write(s)
  15. f.tell() 返回一个整数,表示当前文件的位置(计算字节)。比如:

  16. </>复制代码

    1. >>> f = open("workfile", "r+")
    2. >>> f.write("0123456789abcdef")
    3. >>> f.seek(5) # 到第6个字节
    4. >>> f.read(1)
    5. "5"
    6. >>> f.seek(-3, 2) # 倒数(2表示倒数)第三个字节位置
    7. >>> f.read(1)
    8. "d"
  17. 释放文件资源:

  18. </>复制代码

    1. >>> f.close()
    2. >>> f.read()
    3. Traceback (most recent call last):
    4. File "", line 1, in
    5. ValueError: I/O operation on closed file
  19. 最佳实践是带上with:即便有异常抛出也能释放文件资源

  20. </>复制代码

    1. >>> with open("workfile", "r") as f:
    2. ... read_data = f.read()
    3. >>> f.closed
    4. True
  21. 保存JSON数据
  22. 序列化:将json转为字符串 反序列化:将字符串转为json

  23. </>复制代码

    1. >>> import json
    2. >>> json.dumps([1, "simple", "list"])
    3. "[1, "simple", "list"]"
  24. 将对象序列化到一个文件中:f是一个文件对象

  25. </>复制代码

    1. json.dump(x, f)
  26. 从文件中读取:

  27. </>复制代码

    1. x = json.load(f)
  28. 错误和异常
  29. 语法错误
  30. </>复制代码

    1. >>> while True print "Hello world"
    2. File "", line 1
    3. while True print "Hello world"
    4. ^
    5. SyntaxError: invalid syntax
  31. 执行异常
  32. </>复制代码

    1. >>> 10 * (1/0)
    2. Traceback (most recent call last):
    3. File "", line 1, in
    4. ZeroDivisionError: integer division or modulo by zero
    5. >>> 4 + spam*3
    6. Traceback (most recent call last):
    7. File "", line 1, in
    8. NameError: name "spam" is not defined
    9. >>> "2" + 2
    10. Traceback (most recent call last):
    11. File "", line 1, in
    12. TypeError: cannot concatenate "str" and "int" objects
  33. 处理异常
  34. </>复制代码

    1. >>> while True:
    2. ... try:
    3. ... x = int(raw_input("Please enter a number: "))
    4. ... break
    5. ... except ValueError:
    6. ... print "Oops! That was no valid number. Try again..."
    7. ...
  35. 这里只捕获了ValueError,如果捕获更多异常:

  36. </>复制代码

    1. ... except (RuntimeError, TypeError, NameError):
    2. ... pass
  37. </>复制代码

    1. import sys
    2. try:
    3. f = open("myfile.txt")
    4. s = f.readline()
    5. i = int(s.strip())
    6. except IOError as e:
    7. print "I/O error({0}): {1}".format(e.errno, e.strerror)
    8. except ValueError:
    9. print "Could not convert data to an integer."
    10. except:
    11. print "Unexpected error:", sys.exc_info()[0]
    12. raise
  38. try...except...else..else后面的代码一定会执行

  39. </>复制代码

    1. for arg in sys.argv[1:]:
    2. try:
    3. f = open(arg, "r")
    4. except IOError:
    5. print "cannot open", arg
    6. else:
    7. print arg, "has", len(f.readlines()), "lines"
    8. f.close()
  40. 抛出异常:

  41. </>复制代码

    1. >>> try:
    2. ... raise Exception("spam", "eggs")
    3. ... except Exception as inst:
    4. ... print type(inst) # 异常实例
    5. ... print inst.args # arguments 存储在.args中
    6. ... print inst # __str__方法使得能直接打印参数而不需要引用它。
    7. ... x, y = inst.args
    8. ... print "x =", x
    9. ... print "y =", y
    10. ...
    11. ("spam", "eggs")
    12. ("spam", "eggs")
    13. x = spam
  42. 函数内部的异常也能捕获:

  43. </>复制代码

    1. >>> def this_fails():
    2. ... x = 1/0
    3. ...
    4. >>> try:
    5. ... this_fails()
    6. ... except ZeroDivisionError as detail:
    7. ... print "Handling run-time error:", detail
    8. ...
    9. Handling run-time error: integer division or modulo by zero
  44. 抛出异常
  45. </>复制代码

    1. >>> raise NameError("HiThere")
    2. Traceback (most recent call last):
    3. File "", line 1, in
    4. NameError: HiThere
  46. 不处理异常,直接将异常抛出:

  47. </>复制代码

    1. >>> try:
    2. ... raise NameError("HiThere")
    3. ... except NameError:
    4. ... print "An exception flew by!"
    5. ... raise
    6. ...
    7. An exception flew by!
    8. Traceback (most recent call last):
    9. File "", line 2, in
    10. NameError: HiThere
  48. 自定义异常
  49. </>复制代码

    1. >>> class MyError(Exception):
    2. ... def __init__(self, value):
    3. ... self.value = value
    4. ... def __str__(self):
    5. ... return repr(self.value)
    6. ...
    7. >>> try:
    8. ... raise MyError(2*2)
    9. ... except MyError as e:
    10. ... print "My exception occurred, value:", e.value
    11. ...
    12. My exception occurred, value: 4
    13. >>> raise MyError("oops!")
    14. Traceback (most recent call last):
    15. File "", line 1, in
    16. __main__.MyError: "oops!"
  50. 重写了__init__方法,并且定义了一个value属性。
    一般定义异常的方式是这样的:

  51. </>复制代码

    1. class Error(Exception):
    2. """Base class for exceptions in this module."""
    3. pass
    4. class InputError(Error):
    5. """Exception raised for errors in the input.
    6. Attributes:
    7. expr -- input expression in which the error occurred
    8. msg -- explanation of the error
    9. """
    10. def __init__(self, expr, msg):
    11. self.expr = expr
    12. self.msg = msg
    13. class TransitionError(Error):
    14. """Raised when an operation attempts a state transition that"s not
    15. allowed.
    16. Attributes:
    17. prev -- state at beginning of transition
    18. next -- attempted new state
    19. msg -- explanation of why the specific transition is not allowed
    20. """
    21. def __init__(self, prev, next, msg):
    22. self.prev = prev
    23. self.next = next
    24. self.msg = msg
  52. 清理工作
  53. </>复制代码

    1. >>> try:
    2. ... raise KeyboardInterrupt
    3. ... finally:
    4. ... print "Goodbye, world!"
    5. ...
    6. Goodbye, world!
    7. KeyboardInterrupt
    8. Traceback (most recent call last):
    9. File "", line 2, in
  54. finally总是会被执行,而且如果异常没有被处理的话,在finally里面的代码执行完后会被重新抛出。
    一个更复杂点的例子:

  55. </>复制代码

    1. >>> def divide(x, y):
    2. ... try:
    3. ... result = x / y
    4. ... except ZeroDivisionError:
    5. ... print "division by zero!"
    6. ... else:
    7. ... print "result is", result
    8. ... finally:
    9. ... print "executing finally clause"
    10. ...
    11. >>> divide(2, 1)
    12. result is 2
    13. executing finally clause
    14. >>> divide(2, 0)
    15. division by zero!
    16. executing finally clause
    17. >>> divide("2", "1")
    18. executing finally clause
    19. Traceback (most recent call last):
    20. File "", line 1, in
    21. File "", line 3, in divide
    22. TypeError: unsupported operand type(s) for /: "str" and "str"
  56. 预清理
  57. 一定要带上with保证文件资源被释放

  58. </>复制代码

    1. with open("myfile.txt") as f:
    2. for line in f:
    3. print line,
  59. Python类
  60. 定义类
  61. </>复制代码

    1. class MyClass:
    2. """A simple example class"""
    3. i = 12345
    4. def f(self):
    5. return "hello world"
  62. 引用类的属性和方法
  63. MyClass.i和 MyClass.f
    MyClass.__doc_ => “A simple example class

  64. 定义init方法,设置默认属性
  65. </>复制代码

    1. def __init__(self):
    2. self.data = []
  66. 传递给类的参数会传递给init:

  67. </>复制代码

    1. >>> class Complex:
    2. ... def __init__(self, realpart, imagpart):
    3. ... self.r = realpart
    4. ... self.i = imagpart
    5. ...
    6. >>> x = Complex(3.0, -4.5)
    7. >>> x.r, x.i
    8. (3.0, -4.5)
  68. 类共享变量和实例变量
  69. </>复制代码

    1. class Dog:
    2. kind = "canine" # 类共享变量
    3. def __init__(self, name):
    4. self.name = name # 实例变量
    5. >>> d = Dog("Fido")
    6. >>> e = Dog("Buddy")
    7. >>> d.kind # shared by all dogs
    8. "canine"
    9. >>> e.kind # shared by all dogs
    10. "canine"
    11. >>> d.name # unique to d
    12. "Fido"
    13. >>> e.name # unique to e
    14. "Buddy"
  70. 注意引用变量避免被所有实例共享
  71. </>复制代码

    1. class Dog:
    2. tricks = [] # mistaken use of a class variable
    3. def __init__(self, name):
    4. self.name = name
    5. def add_trick(self, trick):
    6. self.tricks.append(trick)
    7. >>> d = Dog("Fido")
    8. >>> e = Dog("Buddy")
    9. >>> d.add_trick("roll over")
    10. >>> e.add_trick("play dead")
    11. >>> d.tricks # 这里tricks被所有实例共享了
    12. ["roll over", "play dead"]
  72. 正确的用法:

  73. </>复制代码

    1. class Dog:
    2. def __init__(self, name):
    3. self.name = name
    4. self.tricks = [] # creates a new empty list for each dog
    5. def add_trick(self, trick):
    6. self.tricks.append(trick)
    7. >>> d = Dog("Fido")
    8. >>> e = Dog("Buddy")
    9. >>> d.add_trick("roll over")
    10. >>> e.add_trick("play dead")
    11. >>> d.tricks
    12. ["roll over"]
    13. >>> e.tricks
    14. ["play dead"]
  74. 函数的定义可以在类外部(不推荐)
  75. </>复制代码

    1. # Function defined outside the class
    2. def f1(self, x, y):
    3. return min(x, x+y)
    4. class C:
    5. f = f1
    6. def g(self):
    7. return "hello world"
    8. h = g
  76. 通过self引用函数
  77. </>复制代码

    1. class Bag:
    2. def __init__(self):
    3. self.data = []
    4. def add(self, x):
    5. self.data.append(x)
    6. def addtwice(self, x):
    7. self.add(x)
    8. self.add(x)
  78. 每一个值都是一个对象,它的对象存储在object.__class__

  79. 继承
  80. 语法:

  81. </>复制代码

    1. class DerivedClassName(BaseClassName):
    2. .
    3. .
    4. .
  82. 或(moduleName是导入的模块)

  83. </>复制代码

    1. class DerivedClassName(moduleName.BaseClassName):
  84. 如果引用的属性没有在当前类中找到,会找他的基类。继承的类可以重写基类的方法。
    有两个内置的函数很有用:
    判断实例的类型:isinstance(obj, int) 判断是否是继承自int类 ( 如果
    obj.__class__ 是int或者继承自int类 返回true)
    issubclass(bool, int): 判断bool是否是int的子类

  85. 多继承
  86. </>复制代码

    1. class DerivedClassName(Base1, Base2, Base3):
    2. .
    3. .
    4. .
  87. 私有变量和类内引用
  88. 私有变量一般是以_下划线开头
    内部调用方法__双下划线开头:

  89. </>复制代码

    1. class Mapping:
    2. def __init__(self, iterable):
    3. self.items_list = []
    4. self.__update(iterable)
    5. def update(self, iterable):
    6. for item in iterable:
    7. self.items_list.append(item)
    8. __update = update # 拷贝一份update方法
    9. class MappingSubclass(Mapping):
    10. def update(self, keys, values): # 子类可以重写update方法 并且不会影响到init方法
    11. for item in zip(keys, values):
    12. self.items_list.append(item)
  90. 异常也是一个类
  91. 语法:

  92. </>复制代码

    1. raise Class, instance
    2. raise instance (raise instance.__class__, instance的简写)
  93. 比如:

  94. </>复制代码

    1. class B:
    2. pass
    3. class C(B):
    4. pass
    5. class D(C):
    6. pass
    7. for c in [B, C, D]:
    8. try:
    9. raise c()
    10. except D:
    11. print "D"
    12. except C:
    13. print "C"
    14. except B:
    15. print "B"
  95. 遍历
  96. 大部分的对象都可以遍历

  97. </>复制代码

    1. for element in [1, 2, 3]:
    2. print element
    3. for element in (1, 2, 3):
    4. print element
    5. for key in {"one":1, "two":2}:
    6. print key
    7. for char in "123":
    8. print char
    9. for line in open("myfile.txt"):
    10. print line,
  98. 内部:for语句调用了iter()方法,然后调用next()方法访问下一个元素,如果没有下一个会抛出StopInteration异常

  99. </>复制代码

    1. >>> s = "abc"
    2. >>> it = iter(s)
    3. >>> it
    4. >>> it.next()
    5. "a"
    6. >>> it.next()
    7. "b"
    8. >>> it.next()
    9. "c"
    10. >>> it.next()
    11. Traceback (most recent call last):
    12. File "", line 1, in
    13. it.next()
    14. StopIteration
  100. 给类增加遍历器:

  101. </>复制代码

    1. class Reverse:
    2. """Iterator for looping over a sequence backwards."""
    3. def __init__(self, data):
    4. self.data = data
    5. self.index = len(data)
    6. def __iter__(self):
    7. return self
    8. def next(self):
    9. if self.index == 0:
    10. raise StopIteration
    11. self.index = self.index - 1
    12. return self.data[self.index]
  102. 使用:

  103. </>复制代码

    1. >>> rev = Reverse("spam")
    2. >>> iter(rev)
    3. <__main__.Reverse object at 0x00A1DB50>
    4. >>> for char in rev:
    5. ... print char
    6. ...
    7. m
    8. a
    9. p
    10. s
  104. 标准库相关
  105. 系统接口
  106. </>复制代码

    1. >>> import os
    2. >>> os.getcwd() # 返回当前目录
    3. "C:Python26"
    4. >>> os.chdir("/server/accesslogs") # 改变工作目录
    5. >>> os.system("mkdir today") # 运行shell命令:mkdir
    6. 0
  107. </>复制代码

    1. >>> import os
    2. >>> dir(os)
    3. >>> help(os)
  108. 文件操作:

  109. </>复制代码

    1. >>> import shutil
    2. >>> shutil.copyfile("data.db", "archive.db")
    3. >>> shutil.move("/build/executables", "installdir")
  110. 文件通配符
  111. </>复制代码

    1. >>> import glob
    2. >>> glob.glob("*.py")
    3. ["primes.py", "random.py", "quote.py"]
  112. 命令行参数
  113. 比如我们跑了这个命令:python demo.py one two three
    demo.py里面的写法是:

  114. </>复制代码

    1. >>> import sys
    2. >>> print sys.argv
    3. ["demo.py", "one", "two", "three"]
  115. getopt模块和argparse模块提供了更多灵活的方式访问命令行参数

  116. 退出程序和打印错误
  117. sys.exit()
    打印错误:

  118. </>复制代码

    1. >>> sys.stderr.write("Warning, log file not found starting a new one
    2. ")
    3. Warning, log file not found starting a new one
  119. 字符串匹配
  120. </>复制代码

    1. >>> import re
    2. >>> re.findall(r"f[a-z]*", "which foot or hand fell fastest")
    3. ["foot", "fell", "fastest"]
    4. >>> re.sub(r"([a-z]+) 1", r"1", "cat in the the hat")
    5. "cat in the hat"
  121. </>复制代码

    1. >>> "tea for too".replace("too", "two")
    2. "tea for two"
  122. 数学
  123. </>复制代码

    1. >>> import math
    2. >>> math.cos(math.pi / 4.0)
    3. 0.70710678118654757
    4. >>> math.log(1024, 2)
    5. 10.0
  124. </>复制代码

    1. >>> import random
    2. >>> random.choice(["apple", "pear", "banana"])
    3. "apple"
    4. >>> random.sample(xrange(100), 10) # sampling without replacement
    5. [30, 83, 16, 4, 8, 81, 41, 50, 18, 33]
    6. >>> random.random() # random float
    7. 0.17970987693706186
    8. >>> random.randrange(6) # random integer chosen from range(6)
    9. 4
  125. 网络访问
  126. </>复制代码

    1. >>> import urllib2
    2. >>> for line in urllib2.urlopen("http://tycho.usno.navy.mil/cgi-bin/timer.pl"):
    3. ... if "EST" in line or "EDT" in line: # look for Eastern Time
    4. ... print line

    5. Nov. 25, 09:43:32 PM EST
    6. >>> import smtplib
    7. >>> server = smtplib.SMTP("localhost")
    8. >>> server.sendmail("soothsayer@example.org", "jcaesar@example.org",
    9. ... """To: jcaesar@example.org
    10. ... From: soothsayer@example.org
    11. ...
    12. ... Beware the Ides of March.
    13. ... """)
    14. >>> server.quit()
  127. 日期
  128. </>复制代码

    1. >>> # dates are easily constructed and formatted
    2. >>> from datetime import date
    3. >>> now = date.today()
    4. >>> now
    5. datetime.date(2003, 12, 2)
    6. >>> now.strftime("%m-%d-%y. %d %b %Y is a %A on the %d day of %B.")
    7. "12-02-03. 02 Dec 2003 is a Tuesday on the 02 day of December."
    8. >>> # dates support calendar arithmetic
    9. >>> birthday = date(1964, 7, 31)
    10. >>> age = now - birthday
    11. >>> age.days
    12. 14368
  129. 数据压缩
  130. </>复制代码

    1. >>> import zlib
    2. >>> s = "witch which has which witches wrist watch"
    3. >>> len(s)
    4. 41
    5. >>> t = zlib.compress(s)
    6. >>> len(t)
    7. 37
    8. >>> zlib.decompress(t)
    9. "witch which has which witches wrist watch"
    10. >>> zlib.crc32(s)
    11. 226805979
  131. 性能测试
  132. </>复制代码

    1. >>> from timeit import Timer
    2. >>> Timer("t=a; a=b; b=t", "a=1; b=2").timeit()
    3. 0.57535828626024577
    4. >>> Timer("a,b = b,a", "a=1; b=2").timeit()
    5. 0.54962537085770791
  133. 质量控制
  134. 运行文档内的测试代码:

  135. </>复制代码

    1. def average(values):
    2. """Computes the arithmetic mean of a list of numbers.
    3. >>> print average([20, 30, 70])
    4. 40.0
    5. """
    6. return sum(values, 0.0) / len(values)
    7. import doctest
    8. doctest.testmod() # automatically validate the embedded tests
  136. 运行测试集:

  137. </>复制代码

    1. import unittest
    2. class TestStatisticalFunctions(unittest.TestCase):
    3. def test_average(self):
    4. self.assertEqual(average([20, 30, 70]), 40.0)
    5. self.assertEqual(round(average([1, 5, 7]), 1), 4.3)
    6. with self.assertRaises(ZeroDivisionError):
    7. average([])
    8. with self.assertRaises(TypeError):
    9. average(20, 30, 70)
    10. unittest.main() # Calling from the command line invokes all tests
  138. 格式化输出
  139. </>复制代码

    1. >>> import repr
    2. >>> repr.repr(set("supercalifragilisticexpialidocious"))
    3. "set(["a", "c", "d", "e", "f", "g", ...])"
  140. 自动换行和格式化:

  141. </>复制代码

    1. >>> import pprint
    2. >>> t = [[[["black", "cyan"], "white", ["green", "red"]], [["magenta",
    3. ... "yellow"], "blue"]]]
    4. ...
    5. >>> pprint.pprint(t, width=30)
    6. [[[["black", "cyan"],
    7. "white",
    8. ["green", "red"]],
    9. [["magenta", "yellow"],
    10. "blue"]]]
  142. 限制宽度输出:

  143. </>复制代码

    1. >>> import textwrap
    2. >>> doc = """The wrap() method is just like fill() except that it returns
    3. ... a list of strings instead of one big string with newlines to separate
    4. ... the wrapped lines."""
    5. ...
    6. >>> print textwrap.fill(doc, width=40)
    7. The wrap() method is just like fill()
    8. except that it returns a list of strings
    9. instead of one big string with newlines
    10. to separate the wrapped lines.
  144. 本地化输出:

  145. </>复制代码

    1. >>> import locale
    2. >>> locale.setlocale(locale.LC_ALL, "English_United States.1252")
    3. "English_United States.1252"
    4. >>> conv = locale.localeconv() # get a mapping of conventions
    5. >>> x = 1234567.8
    6. >>> locale.format("%d", x, grouping=True)
    7. "1,234,567"
    8. >>> locale.format_string("%s%.*f", (conv["currency_symbol"],
    9. ... conv["frac_digits"], x), grouping=True)
    10. "$1,234,567.80"
  146. 模板
  147. </>复制代码

    1. >>> from string import Template
    2. >>> t = Template("${village}folk send $$10 to $cause.")
    3. >>> t.substitute(village="Nottingham", cause="the ditch fund")
    4. "Nottinghamfolk send $10 to the ditch fund."
  148. substitute会替换模板的关键字。如果传递的参数不对会报异常,建议用safe_substitute:

  149. </>复制代码

    1. >>> t = Template("Return the $item to $owner.")
    2. >>> d = dict(item="unladen swallow")
    3. >>> t.substitute(d)
    4. Traceback (most recent call last):
    5. ...
    6. KeyError: "owner"
    7. >>> t.safe_substitute(d)
    8. "Return the unladen swallow to $owner."
  150. 自定义分隔符号:

  151. </>复制代码

    1. >>> import time, os.path
    2. >>> photofiles = ["img_1074.jpg", "img_1076.jpg", "img_1077.jpg"]
    3. >>> class BatchRename(Template):
    4. ... delimiter = "%"
    5. >>> fmt = raw_input("Enter rename style (%d-date %n-seqnum %f-format): ")
    6. Enter rename style (%d-date %n-seqnum %f-format): Ashley_%n%f
    7. >>> t = BatchRename(fmt)
    8. >>> date = time.strftime("%d%b%y")
    9. >>> for i, filename in enumerate(photofiles):
    10. ... base, ext = os.path.splitext(filename)
    11. ... newname = t.substitute(d=date, n=i, f=ext)
    12. ... print "{0} --> {1}".format(filename, newname)
    13. img_1074.jpg --> Ashley_0.jpg
    14. img_1076.jpg --> Ashley_1.jpg
    15. img_1077.jpg --> Ashley_2.jpg
  152. 多线程
  153. </>复制代码

    1. import threading, zipfile
    2. class AsyncZip(threading.Thread):
    3. def __init__(self, infile, outfile):
    4. threading.Thread.__init__(self)
    5. self.infile = infile
    6. self.outfile = outfile
    7. def run(self):
    8. f = zipfile.ZipFile(self.outfile, "w", zipfile.ZIP_DEFLATED)
    9. f.write(self.infile)
    10. f.close()
    11. print "Finished background zip of: ", self.infile
    12. background = AsyncZip("mydata.txt", "myarchive.zip")
    13. background.start()
    14. print "The main program continues to run in foreground."
    15. background.join() # Wait for the background task to finish
    16. print "Main program waited until background was done."
  154. 建议用单线程,然后Queue模块实现多线程的操作,更加容易试错和设计。

  155. 日志
  156. </>复制代码

    1. import logging
    2. logging.debug("Debugging information")
    3. logging.info("Informational message")
    4. logging.warning("Warning:config file %s not found", "server.conf")
    5. logging.error("Error occurred")
    6. logging.critical("Critical error -- shutting down")
  157. 弱引用
  158. </>复制代码

    1. >>> import weakref, gc
    2. >>> class A:
    3. ... def __init__(self, value):
    4. ... self.value = value
    5. ... def __repr__(self):
    6. ... return str(self.value)
    7. ...
    8. >>> a = A(10) # 创建一个引用
    9. >>> d = weakref.WeakValueDictionary()
    10. >>> d["primary"] = a # 不会创建引用
    11. >>> d["primary"] #
    12. 10
    13. >>> del a # 删除
    14. >>> gc.collect() # 运行垃圾回收
    15. 0
    16. >>> d["primary"] # 这个时候访问会报错
    17. Traceback (most recent call last):
    18. File "", line 1, in
    19. d["primary"]
    20. File "C:/python26/lib/weakref.py", line 46, in __getitem__
    21. o = self.data[key]()
    22. KeyError: "primary"
  159. Lists相关工具集
  160. 队列:

  161. </>复制代码

    1. >>> from collections import deque
    2. >>> d = deque(["task1", "task2", "task3"])
    3. >>> d.append("task4")
    4. >>> print "Handling", d.popleft()
    5. Handling task1
  162. 操作排序:已经排序的插入一个元素

  163. </>复制代码

    1. >>> import bisect
    2. >>> scores = [(100, "perl"), (200, "tcl"), (400, "lua"), (500, "python")]
    3. >>> bisect.insort(scores, (300, "ruby"))
    4. >>> scores
    5. [(100, "perl"), (200, "tcl"), (300, "ruby"), (400, "lua"), (500, "python")]
  164. 精确的浮点操作:
  165. </>复制代码

    1. >>> from decimal import *
    2. >>> x = Decimal("0.70") * Decimal("1.05")
    3. >>> x
    4. Decimal("0.7350")
    5. >>> x.quantize(Decimal("0.01")) # round to nearest cent
    6. Decimal(huanying guanzhu : "0.74")
    7. >>> round(.70 * 1.05, 2) # same calculation with floats
    8. 0.73

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/41278.html

相关文章

  • Python爬虫框架scrapy入门指引

    摘要:想爬点数据来玩玩,我想最方便的工具就是了。这框架把采集需要用到的功能全部封装好了,只要写写采集规则其他的就交给框架去处理,非常方便,没有之一,不接受反驳。首先,大概看下这门语言。如果文档看不懂的话,推荐看看这个教程爬虫教程 想爬点数据来玩玩, 我想最方便的工具就是Python scrapy了。 这框架把采集需要用到的功能全部封装好了,只要写写采集规则,其他的就交给框架去处理,非常方便,...

    孙淑建 评论0 收藏0
  • 区块链技术学习指引

    摘要:引言给迷失在如何学习区块链技术的同学一个指引,区块链技术是随比特币诞生,因此要搞明白区块链技术,应该先了解下比特币。但区块链技术不单应用于比特币,还有非常多的现实应用场景,想做区块链应用开发,可进一步阅读以太坊系列。 本文始发于深入浅出区块链社区, 原文:区块链技术学习指引 原文已更新,请读者前往原文阅读 本章的文章越来越多,本文是一个索引帖,方便找到自己感兴趣的文章,你也可以使用左侧...

    Cristic 评论0 收藏0
  • sphinx快速入门

    摘要:简介是一个用于快速生成文档的工具,非常适合生成文档。称之为主文档,它被作为欢迎页面。由于是默认的域,所以并不需要特别指出所属的域来。自动生成文档注释支持从源代码中提取文档注释信息,然后生成文档,我们将这称之为。 简介 sphinx是一个用于快速生成文档的工具,非常适合生成Python文档。 它具有以下优点: 支持多种输出格式, 如html,Latex,ePub等。 丰富的扩展 结构化...

    yexiaobai 评论0 收藏0
  • 一张脑图看懂BUI Webapp移动快速开发框架【下】--快速入门指引

    摘要:例如改成例如改成以上两种开发方式都可以结合原生平台打包成独立应用。 继上一篇一张脑图看懂BUI Webapp移动快速开发框架【上】--框架与工具、资源 大纲 在线查看大纲 思路更佳清晰 1. 框架设计 框架介绍 简介 BUI 是用来快速构建界面交互的UI交互框架, 专注webapp开发, 开发者只需关注业务的开发, 界面的布局及交互交给BUI, 开发出来的应用, 可以嵌入平台 ( Li...

    hzx 评论0 收藏0
  • 入门指引 - PHP手册笔记

    摘要:对于浏览器,的值可能是可以通过调用函数,判断用户代理是否为浏览器。处理表单处理表单的方式很方便,可以使用超全局变量获得数据。使得之中的特殊字符被正确的编码,从而不会被使用者在页面注入标签或者代码。 曾经简单的学习过PHP,看的是《PHP和MySQL Web开发》,还有万能的搜索引擎的帮助。这次准备系统的学习一下,参考资料是PHP Manual。 PHP能做什么 PHP主要用于服务端的脚...

    Reducto 评论0 收藏0

发表评论

0条评论

最新活动
阅读需要支付1元查看
<