- 学习目录
- 编程方法
- 函数定义
- 函数式编程
- *args 及 ** kwargs
- 匿名函数
- 高阶函数
- 列表生成式及生成器
- 装饰器
0x01 编程方法
- 面向对象
1、类
2、关键字:class
- 面向过程
1、过程
2、关键字:def
- 函数式编程
1、函数
2、关键字`def`开头
3、函数名
4、参数
5、冒号(:)结尾
0x02 函数定义
- 函数定义示例
2.1 定义格式
def function(arg1, arg2, ...):
pass
2.2 定义函数
def test(x):
""" 函数描述 """
x += 1
return x
2.3 函数格式分析
def: 定义函数关键字
test:函数名
(): 定义形参
"" 文档描述 "": 函数描述信息
x += 1: 代码块或程序处理逻辑
return: 定义返回值
2.4 定义函数及过程
# 定义函数
def func1():
""" testing1 """
print("This is func1")
return 0
# 定义过程
def func2():
""" testing2 """
print("This is Func2")
# 调用函数
x = func1
# 调用过程
y = func2
# 输出
print("From Func1 return is %s" %x)
print("From Func2 return is {0}".format(y))
2.5 函数关键字
def # 定义函数
return # 返回值
pass # 通过,不用执行
exit(1) # 直接退出
0x03 函数式编程
< --- 待完善 --- >
0x04 *args 及 ** kwargs
- 调用含义
*args # 代表tuple
**kwargs # 代表dict
- 定义格式
def fun(a, *args, **kwargs):
pass
- args 及 kwargs 传值
def test(m, *args, **kwargs):
print("m = {0}".format(m))
print("args = {0}".format(args))
print("kwargs = {0}".format(kwargs))
test(10, args=(1, 11, 12))
0x05 匿名函数
lambda x, y: x + y
0x06 高阶函数
- map()
- zip()
- sorted()
- 可以通过代码逻辑实现
- 函数复杂程度及算法没内置高阶函数高
- sorted()
* 格式
sorted(iterable, key, reverse)
iterable # 可迭代对象
key # 排序
reverse # bool类型,为true反序,false为正序
# 返回值为list
- Example: map()
def f(x):
return x + x
print(map(f, [1, 2, 3, 4])) # 打印出map()类型
print(list(map(f, [1, 2, 3, 4]))) # 强制转换成list类型
for i in map(f, [1, 2, 3, 4]):
print(i)
- Example: 手动写函数实现(未执行成功)
def testMap(fun, iter):
l = list()
for i in iter:
l.append(fun(i))
return l
print(testMap(f, [1, 2, 3, 4]))
- Example: zip()
zip(l1, l2) # 高阶函数,dict(zip(l1, l2)) 把l1和l2转换成
mm = dict(a=1,b=10,c=3,d=9)
print sorted(mm.iteritems(), key = lambda d:d[1], reverse = True)
- Example: sorted()
sorted([1, 4, 32, 3, 45, 67, 436, 20])
- Example: sorted()
# 排序key
m = dict(a=1, c=10, b=20, d-15)
print(m)
print(sorted(m))
print(sorted(m.items())) # 以key进行排序并输出value
print(sorted(m.items(), key=lambda x: x[1]) # 以指定值排序
# 循环打印key
for i in m:
print(i)
# 循环打印key,value
for k, v in m.items():
print(k, v)
for i in m.items():
print(i)
# 字典三种初始化方法
d1 = dict(a=1, b=2)
d2 = {"a": 1, "b": 2}
d3 = dict([("a", 1), ("b", 2)])
print(d1, d2, d3)
0x07 列表生成式及生成器
- 列表生成式格式
[exp for val in collection if condition]
- 生成器格式
(exp for val in collection if condition)
- Example: 九宫格(列表生成式实现)
def jgg():
number = list()
for i in range(1, 10):
number.append(i)
for A in [x for x in range(1, 10)]:
for B in [x for x in range(1, 10) if x !=A]:
for C in [x for x in range(1, 10) if x !=B]:
for D in [x for x in range(1, 10) if x !=C]:
for E in [x for x in range(1, 10) if x !=D]:
for F in [x for x in range(1, 10) if x !=E]:
for G in [x for x in range(1, 10) if x !=F]:
for H in [x for x in range(1, 10) if x !=G]:
for I in [x for x in range(1, 10) if x !=H]:
print("A = {0} B = {1} C = {2} D = {3} E = {4} F = {5} G = {6} F = {7} H = {8}".format(A, B, C, D, E, F, G, H))
jgg()
- Example: 生成式与生成器区别(主要观察输出值)
# 生成式
a1 = (x for x in range(1, 10) if x%2==0)
print(a1)
print(next(a1)) # 调用next()移动取元素
for i in a1:
print(i)
# 生成器
a2 = [x for x in range(1, 10) if x%2==0]
print(a2)
0x09 装饰器
- 含义: 本质是函数,用于装饰其他函数,就是为其它函数添加附加功能
- 原则:
* 不能修改被装饰函数源代码
* 不能修改被装饰函数的调用方式
- 常用函数
def test1():
pass
print('logging') # 增加通用功能,每个函数都需要增加该功能
def test2():
pass
print('logging') # v增加通用功能,每个函数都需要增加该功能
test1()
test2()
- 装饰器实现
def logger(): # 定义装饰器函数
print('logging') # 函数体可以独立增加,扩展性强,错误率低
def test1(): # 被装饰源代码
pass
logger() # 调用装饰器
def test2(): # 被装饰源代码
pass
logger() # 调用装饰器
test1()
test2()
实现装饰器知识储备
- 函数即"变量"
- 高阶函数
* 把一个函数名当做实参传给另外一个函数(不修改被装饰函数源代码情况下为其添加功能)
* 返回值中包含函数名- 嵌套函数
- 装饰器函数及调用
import time
# 装饰器
def timmer(func):
def warpper(*args, **kwargs):
starttime = time.time()
func()
stoptime = time.time()
print('The func run time is %s' %(stoptime - starttime))
return warpper
# 调用装饰圈
@timmer
# 定义普通函数
def test():
time.sleep(3)
print('in the test')
# 调用函数
test()
- 装饰器之函数即变量
- 调用报错(函数未定义)
def foo():
print('In the foo')
bar()
foo()
- 调用正常
def foo():
print('In the foo')
bar()
def bar():
print('In the bar')
foo()
- 调用正常(定义函数在调用函数体内)
def bar():
print('In the bar')
def foo():
print('In the foo')
bar()
foo()
- 调用报错(函数定义,在函数调用提外)
def bar():
print('In the bar')
foo()
def foo():
print('In the foo')
bar()
- 匿名函数
num = lambda x:x * 3
print(num(3))
- 装饰器之高阶函数
- 打印函数内存地址
# 把一个函数名当做实参传给另外一个函数(不修改被装饰函数源代码情况下为其添加功能)
import time
def bar():
print('In the bar')
def test(func):
print(func)
test(bar)
- 计算执行函数前后的时间差
# 把一个函数名当做实参传给另外一个函数(不修改被装饰函数源代码情况下为其添加功能)
import time
def bar():
time.sleep(3)
print('In the bar')
def test(func):
starttime = time.time()
func()
stoptime = time.time()
print("The func run time is {0}".format(stoptime - starttime))
test(bar)
- 返回值中包含函数名
# 返回值中包含函数名(不修改函数调用方式)
import time
def bar():
time.sleep(3)
print('In the bar')
def test(func):
print(func)
return func
print(test(bar)) # 注意bar不能带括号
- 实例化函数对象
import time
def bar():
time.sleep(3)
print('In the bar')
def test(func):
print(func)
return func
bar = test(bar) # 实例化对象
t()
嵌套函数
- 两层嵌套
def foo():
print('In the foo')
def bar():
print('In the bar')
bar()
foo()
- 嵌套函数之全局变量和局部变量作用域
x = 0
def foo():
x = 1
print('In the foo')
x = 2
def bar():
print('In the bar')
bar()
foo()
- 装饰器(一)
import time
def timer(func):
def deco():
starttime = time.time()
func()
stoptime = time.time()
print("The func run time is {0}".format(stoptime - starttime))
return deco
@timer
def test1():
time.sleep(3)
print('In the test1')
@timer
def test2():
time.sleep(3)
print("In the test2")
test1()
test2()
0x09 示例
- Example: 阶乘
def jc(n):
if n == 0:
return 1
else:
result = 1
for i in range(1, n+1):
result *= i
return result
def main():
n = 10
count = 0
for i in range(0, n+1):
count += jc(i)
print("Count = {0}".format(count))
if __name__ == '__main__':
main()
- Example:
def f(x, l=[]):
for i in range(x):
l.append(i * i)
print(l)
f(2)
# 结果: [0, 1]
f(3, [3, 2, 1])
# 结果: [3, 2, 1, 0, 1, 4]
f(3)
# 结果: [0, 1, 0, 1, 4]
f(x=3, l=[])
# 结果: [0, 1, 4]
- Example: 函数定义及相关参数
def add1(x, y):
print(x + y)
def add2(x, y):
return x + y
def hello():
exit(1)
print("Hello")
add1(1, 2)
result = add2(1, 2)
print(result)
- Example: