Python之函数参数
1 # -*- coding: utf-8 -*- 2 """ 3 Created on Fri Sep 7 09:13:50 2018 4 5 @author: zhen 6 """ 7 # 默认参数,必须在参数定义末尾 8 def mrcs(name, sex, age=18): 9 print(name, sex, age) 10 11 print('*'*15+'默认参数'+'*'*15) 12 mrcs('liming','man') 13 mrcs('wangli', 'woman', 23) 14 print('='*15+'命名参数'+'='*15) 15 # 命名参数 16 def mmcs(name, sex, age): 17 print(name, sex, age) 18 19 # 传统参数 20 mmcs('zhangsan', 'man', 34) 21 # 命名参数 22 mmcs(name='lisi', sex='man', age=12) 23 # 组合使用时传统参数必须按照参数定义的顺序 24 mmcs('bibi', age=23, sex='woman') 25 # mmcs(age=23, 'bibi', sex='woman') : SyntaxError: positional argument follows keyword argument 26 27 print('-'*15+'可变参数'+'-'*15) 28 # 可变参数,元组 29 def kbcs(name, sex, age, *args): 30 print(name,sex,age) 31 print(args) 32 33 # 不向args传参 34 kbcs('lili', 'woman', 18) 35 # 传入单个参数 36 kbcs('lili', 'woman', 18, 'beautiful') 37 # 传入多个参数 38 kbcs('lili', 'woman', 18, 'beautiful', 'fradom', 2018) 39 40 print('+'*10+'键值对类型的可变参数'+'+'*10) 41 # 键值对类型的可变参数,字典 42 def kb2cs(name, sex, age, **kwargs): 43 print(name,sex,age) 44 print(kwargs) 45 46 # 不向args传参 47 kb2cs('kk', 'man', 21) 48 # 传入单个参数 49 kb2cs('kk', 'man', 21, character='childhood') 50 # 传入多个参数 51 kb2cs('kk', 'man', 21, character='childhood', hobby='free', birthyear=2013) 52 53 print('^'*15+'综合使用'+'^'*15) 54 # 综合使用,默认参数,命名参数,可变参数和键值对类型的可变参数 55 def comprehensive(name, sex='nan', *args, **kwargs): 56 print(name, sex, args, kwargs) 57 58 # SyntaxError: positional argument follows keyword argument :命名参数和键值对类型的可变参数不能同时使用,会产生歧义 59 # comprehensive('liming', sex='man', 'student', 23, hobby='flying', idle=4) 60 comprehensive('liming', 'man', 'student', 23, hobby='flying', idle=4) 61 print('*'*37)
结果: