1 #方法的参数定义和默认参数的定义
2 def ask_ok(prompt, retries=4, complaint='Yes or no, please!'):
3 while True:
4 ok = input(prompt)
5 if ok in ('y', 'ye', 'yes'):
6 print("true");
7 if ok in ('n', 'no', 'nop', 'nope'):
8 return False
9 retries = retries - 1
10 if retries < 0:
11 raise OSError('uncooperative user');#相当于c#中的throw;
12 print(complaint)
13
14 #方法的调用
15 def show():
16 ask_ok("please input docstring");
17
18
19 #默认值的共享
20 def fun(n,args=[]):
21 args.append(n);
22 return args;
23
24 print(fun(2));
25 print(fun(3));#长度加1
26 print(fun(4));#长度加1
27
28
29
30 #除去默认值的累计,->为注释,表示方法的返回值类型
31 def func(n,args=None)->[]:
32 if args is None:
33 args=[];
34 args.append(n);
35 return args;
36
37 print(func(2));
38 print(func(3));#长度1
39 print(func(4));#长度1
40
41
42
43
44 #*当最后一个形参以 **name 形式出现,它接收一个字典 (见映射类型 —— 字典) ,该字典包含了所有未出现在形式参数列表中的关键字参数。
45 #它还可能与 *name 形式的参数(在下一小节中所述)组合使用,*name 接收一个包含所有没有出现在形式参数列表中的位置参数元组。
46 #(*name 必须出现在 ** name 之前。)例如,如果我们定义这样的函数:
47
48 def getInfo(info,*argument,**keywords):
49 print("this is ",info);
50 for msg in argument:
51 print(msg);
52 for kw in keywords:
53 print(kw,":",keywords[kw]);
54
55 getInfo("Limburger", "It's very runny, sir.",
56 "It's really very, VERY runny, sir.",
57 shopkeeper="Michael Palin",
58 client="John Cleese",
59 sketch="Cheese Shop Sketch");
60
61 #参数的分拆
62 def parrot(name="xiaoxiao",age=24):
63 print("my name is",name,end='');
64 print("and my age is ",age,end='');
65
66 student={"name":"jack","age":25};
67 parrot(**student);
68
69 stu=["jack",25];
70 parrot(*stu);
71
72 #pairs = [(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')]
73 #pairs.sort(key=lambda pair: pair[1])
74
75 #lamda表达式的使用,就是逆名函数
76 def sorter(L=None):
77 if L is None:
78 L=[];
79 L.sort(key=lambda pair:pair[1]);
80 return L;
81
82 L = [(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')];
83 print(sorter(L));
84
85 #文档字符串
86 def myfunction():
87 """Do nothing,,,but
88 No,really,,,it doesn't
89 """;
90 pass;
91
92 print(myfunction.__doc__);