函数基础

  1. # 定义函数
  2. def function_name(arg1 [,arg2,...]): # arg1,arg2为形参,形参可以0个或多个
  3. '''函数描述信息'''
  4. # 函数体
  5. ...
  6. # 返回值,不写 默认 return None
  7. # 可返还一个或多个值,多个值时以元组返回
  8. return return_val[, return_val2...]
  9. # 调用函数
  10. function_name(val1) # 实参参数根据函数定义的形参个数来传递

参数

  1. def foo(x, y):
  2. print(x)
  3. print(y)
  4. """根据实参角度分析"""
  5. # 1. 按照位置传值
  6. foo(1, 2)
  7. # 2. 按照关键字传值
  8. foo(x = 1, y = 2)
  9. foo(y = 2, x = 1) # 两种传值结果一致
  10. # 3. 混合用
  11. '按位置传值必须在按关键字传值的前面'
  12. foo(1, y=2) # 打印:1 2
  13. """从形参的角度分析"""
  14. # 1. 位置参数: 必须传值的参数
  15. def foo(x, y):
  16. print(x)
  17. print(y)
  18. foo(1, 2) # 定义两个参数,就必须传两个值
  19. # 2. 默认参数:
  20. '默认参数必须放在位置参数的后面'
  21. def foo(x, y=1):
  22. print(x)
  23. print(y)
  24. foo(1) # 默认参数可以不用传值
  25. foo(1, 2) # 也可以传值

可变参数

  1. '*args'
  2. # *args 放在位置参数后面
  3. def foo(x, *args):
  4. print(x)
  5. print(args)
  6. foo(1,2,3,4,5,'b','c') #x:1 args:(2,3,4,5,'b','c')
  7. '**kwargs'
  8. def foo(x, **kwargs):
  9. print(x)
  10. print(kwargs)
  11. foo(1, a=2, b=3, c=4) # x=1, kwargs={'a':2, 'b':3, 'c':4}

闭包

  • 必须是内部定义的函数
  • 该函数包含对外部作用域而不是全局作用域的引用
  1. def f1(x):
  2. def f2():
  3. print(x)
  4. return f2

装饰器

  1. import time
  2. from functools import wraps
  3. # 无参装饰器
  4. def timmer(func):
  5. @wraps(func)
  6. def wrapper(*args, **kwargs):
  7. """wrapper func"""
  8. start_time = time.time()
  9. res = func(*args, **kwargs)
  10. end_time = time.time()
  11. print('start time %ss' % (end_time - start_time))
  12. return res
  13. @timmer # 相对于 index = timmer(index) == wrapper
  14. def index():
  15. """index func"""
  16. print('index page')
  17. index() # wrapper()
  18. # 打印函数说明
  19. print(index.__doc__) # 不加@wraps时 'wrapper func' 加@wraps时 'index func'
  1. # 有参装饰器
  2. def auth(auth_type):
  3. def wrapper(func):
  4. def inner(*args, **kwargs):
  5. if auth_type == 'file':
  6. # file类型的操作
  7. else auth_type == 'sql':
  8. # sql类型的操作
  9. res = func(*args, **kwargs)
  10. return res
  11. return inner
  12. return wrapper
  13. @auth('file') # @auth('file') => @wrapper => index = wrapper(index) => inner
  14. def index():
  15. print('index page')
  16. index() # inner()
  17. @timmer # 后执行
  18. @auth('file') # 下面先执行
  19. def home():
  20. print('home page')

迭代器

可迭代对象:对象本身有iter方法,iter方法得到迭代器
迭代器:对象.iter()得到的结果就是迭代器,对象有next方法
迭代器的iter方法得到的是迭代器本身

  1. l = [1,2,3,4,5]
  2. i = iter(l) # => i = l.__iter__() 迭代器
  3. while True:
  4. try:
  5. print(next(i)) # => i.__next__(
  6. except StopIteration:
  7. break
  8. # for 使用迭代器实现
  9. for i in l: # l.__iter__()
  10. print(i)

优点:

  1. 迭代器提供了一种不依赖索引的取值方式,这样就可以遍历那些没有索引的可迭代对象(字典、集合、文件)
  2. 迭代器与列表比较,迭代器是惰性计算的,更节省内存

缺点:

  1. 无法获取迭代器的长度,使用不如列表索引取值的灵活
  2. 一次性的,只能往后取值,不能倒着取值

查看可迭代对象与迭代器对象

  1. from collections import Iterable,Iterator
  2. s = "hello"
  3. f = open('1.txt', 'r')
  4. isinstance(s, Iterable) # True 可迭代的对象
  5. isinstance(f, Iterable) # True 可迭代的对象
  6. isinstance(s, Iterator) # False 不是迭代器
  7. isinstance(f, Iterator) # True 是迭代器

生成器

生成器就是一个函数,这个函数内含有yield这个关键字;这个行数执行的结果就是生成器

生成器本质就是迭代器

yield功能:

  1. 相当于把iternext方法封装到函数内部
  2. 与return比,return只能返回一次,而yield能返回多次
  3. 函数暂停已经继续运行的状态是通过yield保存的
  1. def countdown(n):
  2. print('start countdown')
  3. while n > 0:
  4. yield n
  5. n -= 1
  6. print('done')
  7. g = countdown(5) # 生成器就是迭代器
  8. # next(g)
  9. # next()函数执行,遇到yield返回yield的值并停止执行,等待下一次next()调用
  10. for i in g:
  11. print(i)
  12. '''
  13. start countdown
  14. 5
  15. 4
  16. 3
  17. 2
  18. 1
  19. done
  20. '''

yield表达式形式

  1. def eater(name):
  2. print('%s start to eat' % name)
  3. while True:
  4. food = yield
  5. print('%s eat %s' % (name, food))
  6. e = eater('zhangsan')
  7. next(e)
  8. e.send('包子')

列表解析和生成器表达式

  1. # 列表解析
  2. l = [expression for item1 in iterable1 if condition1
  3. for item2 in iterable2 if condition2
  4. ...
  5. for itemN in iterableN if conditionN
  6. ]
  7. # 生成器表达式
  8. g = (expression for item1 in iterable1 if condition1
  9. for item2 in iterable2 if condition2
  10. ...
  11. for itemN in iterableN if conditionN
  12. )

面向过程编程

流水线式的编程思想,在设计程序时,需要把整个流程设计出来

优点:

  1. 体系结构更加清晰
  2. 简化程序的复杂度

缺点:

  1. 可扩展性极其差

内置函数

函数名 功能 备注
abs() 求绝对值
round() baoliu
all() 可迭代对象中每个值的bool值都为True时返回True,否则返回False,如果可迭代对象为空返回True
any() 可迭代对象中每个值的bool值都为True时返回True,否则返回False,如果可迭代对象为空返回False
bin() 十进制数转二级制
hex() 十进制转十六进制
oct() 十进制转八进制
pow() 两个参数:pow(x,y) => x y, 三个参数:pow(x,y,z) => x y % z
reversed() 反转
bool() 判断布尔值
bytes() 把字符串转bytes
callable() 是否可以被调用
chr() 将整数转换成对象的ascii码
ord() 将ascii码转换成整数
dir() 查看对象可调用的方法
help() 查看帮助
divmod() 返回一个元组,divmod(x, y) => (x//y, x%y)
enumerater() 返回一个迭代器,返回一个由(索引, 元素)组成的
hash() 得到哈希值
id() 查看唯一标识
sum() 对可迭代对象求和
sorted() 排序
zip()
frozenset 不可变集合
set() 集合
dit() 字典
tuple() 元组
list() 列表
str() 字符串
int() 整型
float() 浮点型
bool() 布尔
complex() 复数
compile()
eval 执行
complie
exec
以下在面向对象中
classmethod
staticmethod
property
delattr
hasattr
getattr
setattr
  1. # 匿名函数
  2. lambda 参数1 [,参数2 [...,参数N]] : 返回表达式
  1. # min 和 max 的高级用法
  2. dic = {'a': 3, 'b': 1, 'c': 5, 'd': 2}
  3. def get_value(key):
  4. return dic[key]
  5. print(max(dic)) # d
  6. print(max(dic, key = get_value)) # c
  7. # 用匿名函数
  8. print(max(dic, key = lambda k: dic[k]))
  9. # sorted 排序
  10. dic = {'a': 3, 'b': 1, 'c': 5, 'd': 2}
  11. print(sorted(dic)) # ['a', 'b', 'c', 'd']
  12. print(sorted(dic, key = lambda k: dic[k])) # ['b', 'd', 'a', 'c']
  13. # map 映射
  14. l = [1,2,4,6,8]
  15. m = map(lambda item: item+1, l)
  16. print(list(m)) # [2, 3, 5, 7, 9]
  17. # reduce 合并
  18. # reduce(函数, 序列, 初始值=0)
  19. from functools import reduce # python3需要导入
  20. l = range(100)
  21. print(reduce(lambda x,y: x+y, l)) # 4950
  22. # filter 过滤
  23. goods = [
  24. {'name':'iPhone', 'price': 8000},
  25. {'name': 'coffee', 'price': 60},
  26. {'name': 'tea', 'price': 260}
  27. ]
  28. f = filter(lambda dic: dic['price'] > 100, goods)
  29. print(list[f]) # [{'name': 'iPhone', 'price': 8000}, {'name': 'tea', 'price': 260}]
  30. # __import__()
  31. # 通过字符串导入模块
  32. s = 'time'
  33. time = __import__(s) # 等同 import time