Python 函数的参数

冷不防 2022-06-17 13:09 315阅读 0赞

使用位置参数

有时候,方法接收的参数数目可能不一定,比如定义一个求和的方法,至少要接收两个参数:

  1. def sum(a, b):
  2. return a + b
  3. # 正常使用
  4. sum(1, 2) # 3
  5. # 但如果我想求很多数的总和,而将参数全部代入是会报错的,而一次一次代入又太麻烦
  6. sum(1, 2, 3, 4, 5) # sum() takes 2 positional arguments but 5 were given

对于这种接收参数数目不一定,而且不在乎参数传入顺序的函数,则应该利用位置参数*args:

  1. def sum(*args):
  2. result = 0
  3. for num in args:
  4. result += num
  5. return result
  6. sum(1, 2) # 3
  7. sum(1, 2, 3, 4, 5) # 15
  8. # 同时,也可以直接把一个数组带入,在带入时使用 * 进行解构
  9. sum(*[1, 2, 3, 4, 5]) # 15

但要注意的是,不定长度的参数args在传递给函数时,需要先转换成元组tuple。这意味着,如果你将一个生成器作为参数带入到函数中,生成器将会先遍历一遍,转换为元组。这可能会消耗大量内存:

  1. def get_nums():
  2. for num in range(10):
  3. yield num
  4. nums = get_nums()
  5. sum(*nums) # 45
  6. # 但在需要遍历的数目较多时,会占用大量内存

使用关键字参数

  • 关键字参数可提高代码可读性
  • 可以通过关键字参数给函数提供默认值
  • 便于扩充函数参数

定义只能使用关键字参数的函数

  • 普通的方式,在调用时不会强制要求使用关键字参数

    定义一个方法,它的作用是遍历一个数组,找出等于(或不等于)目标元素的 index

    def get_indexs(array, target=’’, judge=True):

    1. for index, item in enumerate(array):
    2. if judge and item == target:
    3. yield index
    4. elif not judge and item != target:
    5. 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):

    1. for index, item in enumerate(array):
    2. if judge and item == target:
    3. yield index
    4. elif not judge and item != target:
    5. 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):

    1. target = kwargs.pop('target', '')
    2. judge = kwargs.pop('judge', True)
    3. for index, item in enumerate(array):
    4. if judge and item == target:
    5. yield index
    6. elif not judge and item != target:
    7. 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

关于参数的默认值

算是老生常谈了:函数的默认值只会在程序加载模块并读取到该函数的定义时设置一次

也就是说,如果给某参数赋予动态的值( 比如[]或者{}),则如果之后在调用函数的时候给参数赋予了其他参数,则以后再调用这个函数的时候,之前定义的默认值将会改变,成为上一次调用时赋予的值:

  1. def get_default(value=[]):
  2. return value
  3. result = get_default()
  4. result.append(1)
  5. result2 = get_default()
  6. result2.append(2)
  7. print(result) # [1, 2]
  8. print(result2) # [1, 2]
  9. 因此,更推荐使用None作为默认参数,在函数内进行判断之后赋值:
  10. def get_default(value=None):
  11. if value is None:
  12. return []
  13. return value
  14. result = get_default()
  15. result.append(1)
  16. result2 = get_default()
  17. result2.append(2)
  18. print(result) # [1]
  19. print(result2) # [2]

发表评论

表情:
评论列表 (有 0 条评论,315人围观)

还没有评论,来说两句吧...

相关阅读

    相关 Python 函数参数

    使用位置参数 有时候,方法接收的参数数目可能不一定,比如定义一个求和的方法,至少要接收两个参数: def sum(a, b): return a

    相关 python函数参数

    Python的函数定义中除了正常定义的必选参数外,还可以使用默认参数、可变参数和关键字参数 1、必选参数:须以正确的顺序传入函数。调用时的数量必须和声明时的一样。调用函数是必

    相关 Python函数参数

    定义函数的时候,我们把参数的名字和位置确定下来,函数的接口定义就完成了。对于函数的调用者来说,只需要知道如何传递正确的参数,以及函数将返回什么样的值就够了,函数内部的复杂逻辑被