02.17-functions
函数
接收不定参数
使用如下方法,可以使函数接受不定数目的参数:
def add(x, *args):
total = x
for arg in args:
total += arg
return total
这里,*args
表示参数数目不定,可以看成一个元组,把第一个参数后面的参数当作元组中的元素。
print (add(1, 2, 3, 4))
print (add(1, 2))
10
3
这样定义的函数不能使用关键词传入参数,要使用关键词,可以这样:
def add(x, **kwargs):
total = x
for arg, value in kwargs.items():
print ("adding ", arg)
total += value
return total
print (add(10, y=11, z=12, w=13))
adding y
adding z
adding w
46
再看这个例子,可以接收任意数目的位置参数和键值对参数:
def foo(*args, **kwargs):
print (args, kwargs)
foo(2, 3, x='bar', z=10)
(2, 3) {'x': 'bar', 'z': 10}
不过要按顺序传入参数,先传入位置参数 args ,在传入关键词参数 kwargs 。
返回多个值
函数可以返回多个值:
from math import atan2
def to_polar(x, y):
r = (x**2 + y**2) ** 0.5
theta = atan2(y, x)
return r, theta
r, theta = to_polar(3, 4)
print (r, theta)
5.0 0.9272952180016122
事实上,Python将返回的两个值变成了元组:
print (to_polar(3, 4))
(5.0, 0.9272952180016122)
因为这个元组中有两个值,所以可以使用
r, theta = to_polar(3, 4)
给两个值赋值。
列表也有相似的功能:
a, b, c = [1, 2, 3]
print (a, b, c)
1 2 3
事实上,不仅仅返回值可以用元组表示,也可以将参数用元组以这种方式传入:
def add(x, y):
"""Add two numbers"""
a = x + y
return a
z = (2, 3)
print (add(*z))
5
这里的*
必不可少。
事实上,还可以通过字典传入参数来执行函数:
def add(x, y):
"""Add two numbers"""
a = x + y
return a
w = {'x': 2, 'y': 3}
print (add(**w))
5
map 方法生成序列
可以通过 map
的方式利用函数来生成序列:
def sqr(x):
return x ** 2
a = [2,3,4]
# print (map(sqr, a))
print (list(map(sqr, a)))
[4, 9, 16]
其用法为:
map(aFun, aSeq)
将函数 aFun
应用到序列 aSeq
上的每一个元素上,返回一个列表,不管这个序列原来是什么类型。
事实上,根据函数参数的多少,map
可以接受多组序列,将其对应的元素作为参数传入函数:
def add(x, y):
return x + y
a = (2,3,4)
b = [10,5,3]
print (map(add,a,b))
<map object at 0x0000023740E9D0F0>
02.18-modules-and-packages
模块和包
Python会将所有 .py
结尾的文件认定为Python代码文件,考虑下面的脚本 ex1.py
:
%%writefile ex1.py
PI = 3.1416
def sum(lst):
tot = lst[0]
for value in lst[1:]:
tot = tot + value
return tot
w = [0, 1, 2, 3]
print (sum(w), PI)
Writing ex1.py
可以执行它:
%run ex1.py
6 3.1416
这个脚本可以当作一个模块,可以使用import
关键词加载并执行它(这里要求ex1.py
在当前工作目录):
import ex1
6 3.1416
ex1
<module 'ex1' from 'C:\\Users\\吴旭琴\\Downloads\\python入门笔记(强烈推荐)\\ex1.py'>
在导入时,Python会执行一遍模块中的所有内容。
ex1.py
中所有的变量都被载入了当前环境中,不过要使用
ex1.变量名
的方法来查看或者修改这些变量:
print (ex1.PI)
3.1416
ex1.PI = 3.141592653
print (ex1.PI)
3.141592653
print (ex1.PI)
3.141592653
还可以用
ex1.函数名
调用模块里面的函数:
print (ex1.sum([2, 3, 4]))
9
为了提高效率,Python只会载入模块一次,已经载入的模块再次载入时,Python并不会真正执行载入操作,哪怕模块的内容已经改变。
例如,这里重新导入 ex1
时,并不会执行 ex1.py
中的 print
语句:
import ex1
需要重新导入模块时,可以使用reload
强制重新载入它,例如:
import importlib
importlib.reload(ex1)
6 3.1416
<module 'ex1' from 'C:\\Users\\吴旭琴\\Downloads\\python入门笔记(强烈推荐)\\ex1.py'>
删除之前生成的文件:
import os
os.remove('ex1.py')
__name__
属性
有时候我们想将一个 .py
文件既当作脚本,又能当作模块用,这个时候可以使用 __name__
这个属性。
只有当文件被当作脚本执行的时候, __name__
的值才会是 '__main__'
,所以我们可以:
%%writefile ex2.py
PI = 3.1416
def sum(lst):
""" Sum the values in a list
"""
tot = 0
for value in lst:
tot = tot + value
return tot
def add(x, y):
" Add two values."
a = x + y
return a
def test():
w = [0,1,2,3]
assert(sum(w) == 6)
print ('test passed.')
if __name__ == '__main__':
test()
Overwriting ex2.py
运行文件:
%run ex2.py
test passed.
当作模块导入, test()
不会执行:
import ex2
但是可以使用其中的变量:
ex2.PI
3.1416
使用别名:
import ex2 as e2
e2.PI
3.1416
其他导入方法
可以从模块中导入变量:
from ex2 import add, PI
使用 from
后,可以直接使用 add
, PI
:
add(2, 3)
5
或者使用 *
导入所有变量:
from ex2 import *
add(3, 4.5)
7.5
这种导入方法不是很提倡,因为如果你不确定导入的都有哪些,可能覆盖一些已有的函数。
删除文件:
import os
os.remove('ex2.py')
包
假设我们有这样的一个文件夹:
foo/
__init__.py
bar.py
(defines func)baz.py
(defines zap)
这意味着 foo 是一个包,我们可以这样导入其中的内容:
from foo.bar import func
from foo.baz import zap
bar
和 baz
都是 foo
文件夹下的 .py
文件。
导入包要求:
- 文件夹
foo
在Python的搜索路径中 __init__.py
表示foo
是一个包,它可以是个空文件。
常用的标准库
- re 正则表达式
- copy 复制
- math, cmath 数学
- decimal, fraction
- sqlite3 数据库
- os, os.path 文件系统
- gzip, bz2, zipfile, tarfile 压缩文件
- csv, netrc 各种文件格式
- xml
- htmllib
- ftplib, socket
- cmd 命令行
- pdb
- profile, cProfile, timeit
- collections, heapq, bisect 数据结构
- mmap
- threading, Queue 并行
- multiprocessing
- subprocess
- pickle, cPickle
- struct
PYTHONPATH设置
Python的搜索路径可以通过环境变量PYTHONPATH设置,环境变量的设置方法依操作系统的不同而不同,具体方法可以网上搜索。