Python 函数的参数
使用位置参数
有时候,方法接收的参数数目可能不一定,比如定义一个求和的方法,至少要接收两个参数:
def sum(a, b):
return a + b
# 正常使用
sum(1, 2) # 3
# 但如果我想求很多数的总和,而将参数全部代入是会报错的,而一次一次代入又太麻烦
sum(1, 2, 3, 4, 5) # sum() takes 2 positional arguments but 5 were given
对于这种接收参数数目不一定,而且不在乎参数传入顺序的函数,则应该利用位置参数*args:
def sum(*args):
result = 0
for num in args:
result += num
return result
sum(1, 2) # 3
sum(1, 2, 3, 4, 5) # 15
# 同时,也可以直接把一个数组带入,在带入时使用 * 进行解构
sum(*[1, 2, 3, 4, 5]) # 15
但要注意的是,不定长度的参数args在传递给函数时,需要先转换成元组tuple。这意味着,如果你将一个生成器作为参数带入到函数中,生成器将会先遍历一遍,转换为元组。这可能会消耗大量内存:
def get_nums():
for num in range(10):
yield num
nums = get_nums()
sum(*nums) # 45
# 但在需要遍历的数目较多时,会占用大量内存
使用关键字参数
- 关键字参数可提高代码可读性
- 可以通过关键字参数给函数提供默认值
- 便于扩充函数参数
定义只能使用关键字参数的函数
普通的方式,在调用时不会强制要求使用关键字参数
定义一个方法,它的作用是遍历一个数组,找出等于(或不等于)目标元素的 index
def get_indexs(array, target=’’, judge=True):
for index, item in enumerate(array):
if judge and item == target:
yield index
elif not judge and item != target:
yield index
array = [1, 2, 3, 4, 1]
下面这些都是可行的
result = get_indexs(array, target=1, judge=True)
print(list(result)) # [0, 4]
result = get_indexs(array, 1, True)
print(list(result)) # [0, 4]
result = get_indexs(array, 1)
print(list(result)) # [0, 4]使用 Python3 中强制关键字参数的方式
定义一个方法,它的作用是遍历一个数组,找出等于(或不等于)目标元素的 index
def get_indexs(array, *, target=’’, judge=True):
for index, item in enumerate(array):
if judge and item == target:
yield index
elif not judge and item != target:
yield index
array = [1, 2, 3, 4, 1]
这样可行
result = get_indexs(array, target=1, judge=True)
print(list(result)) # [0, 4]也可以忽略有默认值的参数
result = get_indexs(array, target=1)
print(list(result)) # [0, 4]但不指定关键字参数则报错
get_indexs(array, 1, True)
TypeError: get_indexs() takes 1 positional argument but 3 were given
使用 Python2 中强制关键字参数的方式
定义一个方法,它的作用是遍历一个数组,找出等于(或不等于)目标元素的 index
使用 **kwargs,代表接收关键字参数,函数内的 kwargs 则是一个字典,传入的关键字参数作为键值对的形式存在
def get_indexs(array, **kwargs):
target = kwargs.pop('target', '')
judge = kwargs.pop('judge', True)
for index, item in enumerate(array):
if judge and item == target:
yield index
elif not judge and item != target:
yield index
array = [1, 2, 3, 4, 1]
这样可行
result = get_indexs(array, target=1, judge=True)
print(list(result)) # [0, 4]也可以忽略有默认值的参数
result = get_indexs(array, target=1)
print(list(result)) # [0, 4]但不指定关键字参数则报错
get_indexs(array, 1, True)
TypeError: get_indexs() takes 1 positional argument but 3 were given
关于参数的默认值
算是老生常谈了:函数的默认值只会在程序加载模块并读取到该函数的定义时设置一次
也就是说,如果给某参数赋予动态的值( 比如[]或者{}),则如果之后在调用函数的时候给参数赋予了其他参数,则以后再调用这个函数的时候,之前定义的默认值将会改变,成为上一次调用时赋予的值:
def get_default(value=[]):
return value
result = get_default()
result.append(1)
result2 = get_default()
result2.append(2)
print(result) # [1, 2]
print(result2) # [1, 2]
因此,更推荐使用None作为默认参数,在函数内进行判断之后赋值:
def get_default(value=None):
if value is None:
return []
return value
result = get_default()
result.append(1)
result2 = get_default()
result2.append(2)
print(result) # [1]
print(result2) # [2]
还没有评论,来说两句吧...