Python函数

编程方式 

  • 面向对象 
    • 类 ==> class
  • 面向过程
    • 过程 ==> def 
  • 函数式编程
    • 函数 ==> def
    • 函数式编程就是先定义一个数学函数,然后按照这个数学模型用编程语言去实现它.

  

 1 #Python函数定义方法
 2 def test(x):
 3     """the function definition"""
 4     x+=1
 5     return
 6 
 7 '''
 8 def: 定义函数的关键字
 9 test: 函数名
10 """ """: 文档描述
11 x+=1: 泛指代码块或程序处理逻辑
12 return: 定义返回值
13 '''

为什么使用函数:

  • 没有函数的编程只是在写逻辑(功能). 函数是把逻辑结构化和过程化的一种编程方法
  • 使用函数有三大优点
    • 代码重用
    • 保持一致性
    • 可扩展性

函数基本语法及特性

 1 # 定义一个python函数
 2 def func1():
 3     """testing"""
 4     print('func1')
 5     return 0
 6 
 7 # 调用此函数
 8 x=func1()
 9 
10 
11 
12 
13 # 定义一个过程(面向过程编程)
14 def func2():
15         """testing2"""
16         print('func2')
17 
18 # 调用此过程函数
19 y=func2() 
20 
21 print('func1 return %s'  %x)  # 返回0
22 print('func2 return %s'  %y)  # 返回None
23 
24 
25 
26 # 过程其实就是没有返回值的函数. 在Python中
 1 # 写日志
 2 
 3 with open('a.txt','a+') as f:
 4    f.write('end action')
 5 
 6 def test1():
 7     print('test1 starting action...')
 8 
 9     with open('a.txt','a+')as f1:
10         f1.write('end action')
11 
12 def test2():
13     print('test2 starting action...')
14 
15     with open('a.txt','a+')as f2:
16         f2.write('end action')
17 
18 def test3():
19     print('test3 starting action...')
20 
21     with open('a.txt','ab')as f3:
22         f3.write('end action')
23 
24 # 用函数优化上一段代码
25 import time
26 def logger():  # 类似日志的功能
27     time_format='%Y-%m-%d %X' # 定义时间戳格式
28     time_current = time.strftime(time_format) # 将当前时间以指定格式显示出来
29     with open('a.txt','a+') as f:
30         f.write('end action
' %time_current)
31 
32 def test1():
33     print('test1 starting action...')
34     logger()
35 
36 def test2():
37     print('test2 starting action...')
38     logger()
39 
40 def test3():
41     print('test3 starting action...')
42     logger()

函数参数调用

 1 # 函数可以没有返回值,可以返回一个值,也可以返回多个值(多个值时,装在元组里返回)
 2 
 3 def test1():
 4     print('in test1')
 5     #没有定义返回值,会返回None
 6 
 7 
 8 def test2():
 9     print('in test2')
10     return 0
11 
12 
13 def test3():
14     print('in test3')
15     return 1,'hello',['alex','wupeiqi'],{'name':'alex'}
16 
17 
18 x = test1()
19 y = test2()
20 z = test3()
21 print(x)
22 print(y)
23 print(z) # 所有返回值会放在元组里返回
 1 # 返回值还可以是一个方法
 2 def test4():
 3     print('in test4')
 4     return test2  # 高级函数. 返回的是test2的地址 <function test2 at 0x0000014808AAA8C8> TODO 有什么用?
 5 
 6 
 7 a = test4()
 8 print(a)
 9 '''
10 函数返回值的作用:
11 方便知道函数执行结果,以备其它程序调用或根据该结果适用不同的逻辑
12 '''

有参函数

  • 固定参数
  • 非固定参数

固定参数

 1 # 有参函数
 2 def test(x, y):  # x, y: 形参
 3     print(x)
 4     print(y)
 5 
 6 test(1,2)  # 1, 2 实参, 与形参一一对应
 7 
 8 test(y=1,x=2) # 关键字调用,跟形参顺序无关
 9 
10 test(3,x=2) # 会报错3是位置参数赋给了x; x=2 通过关键字调用又把2赋值给x, 一个参数x有了多个值.所以会报错.
11 
12 # 关键字参数不能写在位置参数前面
13 test(3, z=2, y=6) #这样写可以
14 test(z=2, y=6, 3) #这样写是不行的, 会报错
15 
16 
17 # 默认参数
18 def test(x, y=2):
19     print(x)
20     print(y)
21 
22 test(1) # 返回1,2 (2是默认的)
23 test(1, y=3) # 也可以改变默认值
24 
25 '''
26 默认参数
27 1 特点:
28   调用函数的时候, 默认函数非必须传递
29 2.用途:
30   比如现在的一键安装,就是都把默认值调好,就可以一键安装.
31   连接数据库的端口号.
32 '''

非固定参数

 1 # 非固定参数 (实参数目不固定)
 2 def test(*args):  # *args接收n个位置参数, 无法接收关键字参数; 转换成元组形式
 3     print(args)
 4 
 5 test(1,2,3,4,5,5) # 多个实参会被放进元组里
 6 test(*[1,2,3,4,5,5]) # args = tuple([1,2,3,4,5])
 7 
 8 def test1(x, *args):
 9     print(x)
10     print(args)
11 
12 test1(1,2,3,4,5,6,7)
13 
14 
15 # 把关键字参数转换成字典的形式
16 def test2(**kwargs):  # 接收n个关键字参数,转换成字典形式
17     print(kwargs)
18     print(kwargs['name']) 
19 
20 test2(name='alex',age=8,sex='f')  # 返回{'name':alex, 'age':8,'sex':'f'}
21 test2(**{'name':'alex', 'age':8})
22 
23 
24 def test3(name, **kwargs):
25     print(name)
26     print(kwargs)
27 
28 test3('alex')# 返回alex, {}
29 test3('alex','xxx') # 会出错, 因为第二个位置要求关键字参数,'xxx'不符合要求
30 
31 
32 def test4(name, age=18, **kwargs):
33     print(name)
34     print(kwargs)
35     
36 test4('alex',sec='m',hobby='test',age=3)
37 
38 '''
39 def test4(name, **kwargs,age=18) : # 这样写是错的, 非固定参数要写在后面
40     print(name)
41     print(kwargs)
42 '''
43 
44 
45 def test5(name, age=18,*args, **kwargs):
46     print(name)
47     print(age)
48     print(args)
49     print(kwargs)
50 
51 
52 test5('alex', age=34, sec='m', hobby='test')
原文地址:https://www.cnblogs.com/cheese320/p/8877679.html