3. 定义函数

定义函数

>>> def fib(n): # write Fibonacci series up to n 
... 	"""Print a Fibonacci series up to n.""" 
... 	a, b = 0, 1 
... 	while a < n: 
... 		print(a, end=’ ’) 
... 		a, b = b, a+b
...		print()
...
>>> # Now call the function we just defined: 
... fib(2000) 
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597

函数体的第一行语句可以是可选的字符串文本,这个字符串是函数的文档字符串,或称为 docstring

注意:函数 调用 会为函数局部变量生成一个新的符号表。 确切的说,所有函数中的变量赋值 都是将值存储在局部符号表。 变量引用首先在局部符号表中查找,然后是包含函数的 局部符号表,然后是全局符号表,最后是内置名字表。 因此,**全局变量不能在函数中 直接赋值(除非用 global 语句命名),尽管他们可以被引用。 **

一个函数定义会在当前符号表内引入函数名。 函数名指代的值(即函数体)有一个被 Python 解释器认定为用户自定义函数的类型。 这个值可以赋予其他的名字(即变量 名),然后它也可以被当做函数使用。 这可以作为通用的重命名机制:

>>> fib <function fib at 10042ed0> 
>>> f = fib 
>>> f(100) 
0 1 1 2 3 5 8 13 21 34 55 89

1、python新功能

>>> def fib2(n): # return Fibonacci series up to n 
... 	"""Return a list containing the Fibonacci series up to n.""" 
... 	result = [] 
... 	a, b = 0, 1 
... 	while a < n:
... 		result.append(a) # see below 
... 		a, b = b, a+b 
... 	return result 
... 
>>> f100 = fib2(100) # call it 
>>> f100 			 # write the result 
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
  • return 语句从函数中返回一个值,不带表达式的 return 返回 None 。过程结束后也会返回 None
  • 语句 result.append(b) 称为链表对象 result 的一个方法 ( method )。方法是一个“属于”某个对象的函数,它被命名为 obj.methodename。

2、默认参数值

i = 5
def f(arg=i):
	print(arg)
i = 6
f()
重要警告: 默认值只被赋值一次。这使得当默认值是可变对象时会有所不同,

3、关键字参数

函数可以通过关键字参数的形式来调用,形如keyword = value

parrot(1000) 										# 1 positional argument
parrot(voltage=1000) 								# 1 keyword argument
parrot(voltage=1000000, action=’VOOOOOM’) 			# 2 keyword arguments
parrot(action=’VOOOOOM’, voltage=1000000) 			# 2 keyword arguments
parrot(’a million’, ’bereft of life’, ’jump’) 		# 3 positional arguments
parrot(’a thousand’, state=’pushing up the daisies’)# 1 positional, 1 keyword

4、特殊关键字

引入一个形如**name 的参数时,它接收一个字典,该字典包含了所有未出现在形式参数列表中的关键字参数。这里可能还会组合使用一个形如*name 的形式参数,它接收一个元组,包含了所有没有出现在形式参数列表中的参数值。( *name 必须在**name 之前出现)

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")

5、可变参数列表

​ 这些参数被包装进一个元组,在这些可变个数的参数之前,可以有零到多个普通的参数。通常,这些可变参数是参数列表中的最后一个,因为它们将把所有的剩余输入参数传递给函数。任何出现在*args 后的参数是关键字参数,这意味着,他们只能被用作关键字,而不是位置参数

6、参数列表的分拆

​ 当你要传递的参数已经是一个列表,但要调用的函数却接受分开一个个的参数值。这时候你要把已有的列表拆开来。例如内建函数range() 需要要独立的start , stop参数。你可以在调用函数时加一个*操作符来自动把参数列表拆开:

>>> list(range(3, 6)) # normal call with separate arguments
[3, 4, 5]
>>> args = [3, 6]
>>> list(range(*args)) # call with arguments unpacked from a list
[3, 4, 5]

可以使用**操作符分拆关键字参数为字典:

>>> def parrot(voltage, state=’a stiff’, action=’voom’):
... 	print("-- This parrot wouldn’t", action, end=’ ’)
... 	print("if you put", voltage, "volts through it.", end=’ ’)
... 	print("E’s", state, "!")
...
>>> d = {"voltage": "four million", "state": "bleedin’ demised", "action": "VOOM"}
>>> parrot(**d)
-- This parrot wouldn’t VOOM if you put four million volts through it. E’s bleedin’

7、Lambda形式

通过lambda关键字,可以创建短小的匿名函数。

# 返回两个参数的和
lambda a, b: a + b

Lambda 形式可以用于任何需要的函数对象,它们只能有一个单独的表达式。

8、文档字符串

>>> def my_function():
... 	"""Do nothing, but document it.
...
... 	No, really, it doesn’t do anything.
... 	"""
... 	pass
...
>>> print(my_function.__doc__)
Do nothing, but document it.
	No, really, it doesn’t do anything.
原文地址:https://www.cnblogs.com/BigMario/p/13577459.html