Python —— 快速入门笔记

前一段时间比较忙,就把学到一半 python 搁下了

最近差不多到考试周了,事情也没那么多了,终于可以重新回到战线上啦

搁着的这段时间里,买了本宋吉广翻译的《Python 核心编程》,感觉这本书讲的还挺不错的

买来后直接就看了 “快速入门” 这一章,还真的很快就入门了,基础的语法很快就过了一遍

个人觉得关键点还是异常处理、函数使用、类的使用以及模块使用这几点

下面每个关键点都举个简单例子吧

异常错误处理:打开并读取文件,处理 IO 错误

1
2
3
4
5
6
7
try:
fobj = open(raw_input('Enter file name:'), "r")
for eachLine in fobj:
print eachLine,
fobj.close()
except IOError, e:
print 'file open error:', e

函数:加法操作

1
2
3
4
5
6
def add(x, y = 6):
"this is the documentation"
return x + y

print add(4)
print add(4, 5)

类:一个简单的操作类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
def main():
foo1 = FooClass()
foo1.showname()
foo1.showver()
foo2 = FooClass('Jane Smith')
foo2.showname()

class FooClass(object):
"""my very first class : FooClass"""
version = 0.1
def __init__(self, nm='John Doe'):
"""constructor"""
self.name = nm # class instance (data) attribute
print "Created a class instance for", nm
def showname(self):
"""display instance attribute and class name"""
print "Your name is", self.name
print "My name is", self.__class__.__name__
def showver(self):
"""display class(static) attribute"""
print self.version # reference FooClass.version
def addMe2Me(self, x):
"""apply + operation to argument"""
return x + x

if __name__ == '__main__':
main()

模块:导入外部模块,其实每个 python 文件都是一个模块,模块的名字就是不带. py 后缀的文件名,通过 import 可以导入模块

1
2
3
4
import sys
sys.stdout.write('Hello World\n') # call function
print sys.platform # call variable
print sys.version

另外还有两个比较实用的东西,就是查看 python 帮助

一个是 help,可以在 python 解释器也可以通过执行文件来调用

比如要查看 sys 模块的帮助,就输入

1
help(sys)

注:在调用帮助之前需要先导入模块,也就是 import sys

还有一种方法就是查看模块的定义文档信息

1
sys.stdout.write(sys.__doc__)