3.1 、3.2 script functions
- 函数的使用,代码块的组合
- 接口类型注释:
def read_prices(filename: str) -> dict:
- 局部变量,全局变量
name = 'Dave'
def spam():
global name
name = 'Guido' # Changes the global name above
不建议这种方式,全局变量更改使用class
- 使用空格分隔的文件读取:
rows = csv.reader(f, delimiter=' ')
3.3 error checking
ArithmeticError
AssertionError
EnvironmentError
EOFError
ImportError
IndexError
KeyboardInterrupt
KeyError
MemoryError
NameError
ReferenceError
RuntimeError
SyntaxError
SystemError
TypeError
ValueError
推荐错误捕获方式:
try:
...
except LookupError as e:
...
except RuntimeError as e:
...
except IOError as e:
...
except KeyboardInterrupt as e:
...
或者:
try:
...
except (IOError,LookupError,RuntimeError) as e:
...
不推荐↓,会不知道为什么出问题
try:
...
except Exception: # DANGER. See below
print('An error occurred')
捕获所有错误的话,要显示出来:
try:
go_do_something()
except Exception as e:
print('Computer says no. Reason :', e)
要考虑周全
3.4 Modules
Any Python source file is a module.
三种import的形式:
① 从上到下将foo执行完毕
# foo.py
def grok(a):
...
def spam(b):
# 使用的时候
import foo
a = foo.grok(2)
b = foo.spam('Hello')
② 只是将module的名称在本地改变了一下
import math as m
def rectangular(r, theta):
x = r * m.cos(theta)
y = r * m.sin(theta)
return x, y
③ 依然运行整个module,将函数名本地化,
方便频繁使用的时候:
from math import sin, cos
def rectangular(r, theta):
x = r * cos(theta)
y = r * sin(theta)
return x, y
import执行整个文件;modules为独立的环境
module存放
配置环境的时候,有更改过环境变量的path
>>> import sys
>>> sys.path
[
'',
'/usr/local/lib/python36/python36.zip',
'/usr/local/lib/python36',
...
]
① import自己的py文件
import sys
sys.path.append('/project/foo/pyfiles')
3.5 Main Module
模板template:
# prog.py
# Import statements (libraries)
import modules
# Functions
def spam():
...
def blah():
...
# Main function
def main():
...
if __name__ == '__main__':
main()
Sys.argv[ ]其实就是一个列表,里边的项为用户输入的参数,关键就是要明白这参数是从程序外部输入的,而非代码本身的什么地方,要想看到它的效果就应该 将程序保存了,从外部来运行程序并给出参数。
获取命令行输入的参数的(参数和参数之间空格区分)
#!/usr/bin/env python3
3.6 Design Discussion
代码要写的更加开放,别写死,不要只能适用于一种功能
①不建议
# Provide a filename
def read_data(filename):
records = []
with open(filename) as f:
for line in f:
...
records.append(r)
return records
d = read_data('file.csv')
② 建议,可以适用于不同的格式
# Provide lines
def read_data(lines):
records = []
for line in lines:
...
records.append(r)
return records
with open('file.csv') as f:
d = read_data(f)
不将函数写死
# A CSV file
lines = open('data.csv')
data = read_data(lines)
# A zipped file
lines = gzip.open('data.csv.gz','rt')
data = read_data(lines)
# The Standard Input
lines = sys.stdin
data = read_data(lines)
# A list of strings
lines = ['ACME,50,91.1','IBM,75,123.45', ... ]
data = read_data(lines)