python语法31[函数]
一 简单函数和函数指针
def myadd(a,b):
return a + b;
print(myadd(3,2));
f = myadd;
print(f(20,30));
return a + b;
print(myadd(3,2));
f = myadd;
print(f(20,30));
二 函数的默认参数
def result(r = 2):
if( r == 1):
print('bad')
elif(r == 2):
print('good')
elif(r == 3):
print('great')
result()
result(1)
def f2(a, L=[]):
L.append(a)
return L
print(f2(1))
print(f2(2))
print(f2(3))
def f3(a, L=None):
if L is None:
L = []
L.append(a)
return L
print(f3(1))
print(f3(2))
print(f3(3))
结果:if( r == 1):
print('bad')
elif(r == 2):
print('good')
elif(r == 3):
print('great')
result()
result(1)
def f2(a, L=[]):
L.append(a)
return L
print(f2(1))
print(f2(2))
print(f2(3))
def f3(a, L=None):
if L is None:
L = []
L.append(a)
return L
print(f3(1))
print(f3(2))
print(f3(3))
good
bad
[1]
[1, 2]
[1, 2, 3]
[1]
[2]
[3]
注意:
默认值在程序的整个运行过程中仅评估一次,对于参数为可变类型的要特别注意,例如list,dictionary,大部分的class类型。
跟C++一样,没有默认值的在前,后面的为有默认值。
三 关键字参数和参数打包
def ilike(first, second = 'banana', third = 'apple'):
print("first is ", end = ' '); print(first, end = ', ')
print("second is ", end = ' '); print(second, end = ', ')
print("and third is ", end = ' '); print(third)
ilike('pear');
ilike('pear', second = 'apple', third = 'banana')
ilike( 'ilike', third = 'god')
d = {'third' : 'apple', 'second' : 'pear', "first" : "banana"}
ilike(**d)
print("first is ", end = ' '); print(first, end = ', ')
print("second is ", end = ' '); print(second, end = ', ')
print("and third is ", end = ' '); print(third)
ilike('pear');
ilike('pear', second = 'apple', third = 'banana')
ilike( 'ilike', third = 'god')
d = {'third' : 'apple', 'second' : 'pear', "first" : "banana"}
ilike(**d)
四 任意长度参数和dictionary参数
def cheeseshop(kind, *arguments, **keywords):
print("-- Do you have any", kind, "?")
print("-- I'm sorry, we're all out of", kind)
for arg in arguments: print(arg)
print("-" * 40)
keys = sorted(keywords.keys())
for kw in keys: print(kw, ":", keywords[kw])
cheeseshop("Limburger", "It's very runny, sir.",
"It's really very, VERY runny, sir.",
shopkeeper="Michael Palin",
client="John Cleese",
sketch="Cheese Shop Sketch")
注意:print("-- Do you have any", kind, "?")
print("-- I'm sorry, we're all out of", kind)
for arg in arguments: print(arg)
print("-" * 40)
keys = sorted(keywords.keys())
for kw in keys: print(kw, ":", keywords[kw])
cheeseshop("Limburger", "It's very runny, sir.",
"It's really very, VERY runny, sir.",
shopkeeper="Michael Palin",
client="John Cleese",
sketch="Cheese Shop Sketch")
*参数名字,表示任意个数的参数。
**参数名字,表示dictionary参数。
*参数必须出现在**前面。
五 函数定义lamda表达式
def make_incrementor(n):
return lambda x: x + n
f = make_incrementor(42)
print(f(1))
print(f(2))
注意:这功能高级!return lambda x: x + n
f = make_incrementor(42)
print(f(1))
print(f(2))
完!