Python之路 day3 函数定义 *args及**kwargs

 1 #!/usr/bin/env python
 2 # -*- coding:utf-8 -*- 
 3 #Author:ersa
 4 
 5 import time
 6 
 7 # def logger():
 8 #     time_format = "%Y-%m-%d %X"
 9 #     time_current = time.strftime(time_format)
10 #     with open("log.txt", 'a+') as f:
11 #         f.write("%s end action
" %time_current)
12 #
13 # def test(x,y,z=9):
14 #     print("x = %s"%x)
15 #     print("y = %s" %y)
16 #     print("z = %s" %z)
17 
18 #函数参数说明,位置参数 与形参一一对应
19 # test(1,2)   #位置参数与形参一一对应
20 # test(y=2,x=1)   #y=2,x=1关键字参数调用与形参顺序无关
21 #test(x=2,3)
22 #既有关键字,又有位置的时候,一定要按照位置关系对应
23 #关键字参数不能写在位置参数前面
24 
25 #默认参数特点:挑用函数的时候,默认参数非必传
26 
27 #实参个数不确定的情况下,形参以* 开头定义变量名,将实参转化为元组
28 #*args: 接受n个位置参数,转换成元组的形式
29 # def tests(*args):
30 #     print(args)
31 #
32 # tests(1,2,3,4,5)
33 # tests(*[1,2,3,4,5]) #args=tuple([1,2,3,4,5])
34 #
35 #
36 # def tests1(x,*args):
37 #     print(x)
38 #     print(args)
39 # tests1(1,2,3,4,5)
40 
41 #字典作为函数形参,**kwargs:把n个关键字参数转换成字典的方式
42 #**kwargs 以字典的方式接收参数,字典参数组必须放到后面
43 # def test_dic(name,age=18,**kwargs):
44 #     print(name)
45 #     print(age)
46 #     print(kwargs)
47 #
48 # test_dic('alex',sex='F',hobby='tesla')
49 
50 
51 def args_kwargs(name,age=18,*args,**kwargs):
52     print(name)
53     print(age)
54     print(args)
55     print(kwargs)
56 
57 args_kwargs('alex',34,sex='m',hobby='tesla')
58 
59 """
60 def test1():
61     print("in the test1")
62     logger()
63     return 0
64 
65 def test2():
66     print("in the test2")
67     logger()
68 
69 def test3():
70     print("in the test3")
71     logger()
72     return 1,10,"ersa",['ersa','ma']
73 
74 x = test1()
75 y = test2()
76 z = test3()
77 
78 print(x)
79 print("from test1 return is [%s]"%type(x))
80 print(y)
81 print("from test2 return is [%s]"%type(y))
82 print(z)
83 print("from test3 return is [%s]"%type(z))
84 """
原文地址:https://www.cnblogs.com/iersa/p/6228313.html