python 函数定义
函数
函数是组织好的,可重复使用的,用来实现单一,或相关联功能的代码段。函数能提高应用的模块性,和代码的重复利用率。
函数传值
一、位置参数
def log(message, values):
if not values:
print(message)
else:
values_str = ', '.join(str(x) for x in values)
print('%s: %s' % (message, values_str))
log('My numbers are', [1, 2])
log('Hi there', [])
>>>
My numbers are: 1, 2
Hi there
二、关键字参数
用于函数调用,通过“键-值”形式加以指定。可以让函数更加清晰、容易使用,同时也清除了参数的顺序需求。
# 以下是用关键字参数正确调用函数的实例
print_hello('tanggu', sex=1)
print_hello(sex=1, name='tanggu')
# 以下是错误的调用方式
print_hello(name='tanggu', 1)
print_hello(sex=1, 'tanggu')
三、默认参数
# 正确的默认参数定义方式--> 位置参数在前,默认参数在后
def print_hello(name, sex=1):
....
# 错误的定义方式
def print_hello(sex=1, name):
....
# 调用时不传sex的值,则使用默认值1
print_hello('tanggu')
# 调用时传入sex的值,并指定为2
print_hello('tanggu', 2)
四、 可变参数 *args, **kwargs
*args 接收一个可变长位置参数,类型int、str、tuple、list
def log(message, *args, **kwargs): if not args and not kwargs: print(message) else: values_str = ', '.join(str(x) for x in args) print('%s: %s' % (message, values_str)) log('My numbers are', *(1, 2, 3)) log('My numbers are', 1, 2, 3) >>> My numbers are: 1, 2, 3 My numbers are: 1, 2, 3
**kwargs 接收一个dict或者关键字参数
def log(message, *args, **kwargs): if not args and not kwargs: print(message) else: values_str = ', '.join(str(x) for x in kwargs.values()) print('%s: %s' % (message, values_str)) log('My numbers are', **{"a": 1, "b": 2}) log('My numbers are', a=1, b=2) >>> My numbers are: 1, 2 My numbers are: 1, 2
五、应该使用None来描述具有动态默认值的关键字参数, 而不要使用[],{},()等作为默认值
from datetime import datetime from time import sleep def log(message, when=None): when = datetime.now() if when is None else when print("%s: %s" % (when, message)) log("hi there!") sleep(1) log("hi again!") >>> 2017-06-15 15:36:05.380573: hi there! 2017-06-15 15:36:06.380673: hi again!
六、用只能以关键字形式指定的参数来确保代码明晰
参数列表里的*号,标志着位置参数就此终结,之后的那些参数,都只能以关键字形式来指定。
def safe_division(number, divisor, *, ignore_overflow=False, ignore_zero_division=False): pass safe_division(1, 10**10, True, False) >>> TypeError: safe_division() takes 2 positional arguments but 4 were given
正确的方式:
def safe_division(number, divisor, *, ignore_overflow=False, ignore_zero_division=False): pass safe_division(1, 10**10, ignore_overflow=True)