zoukankan      html  css  js  c++  java
  • 函数传参时,默认参数为变量容易出现的问题

    在定义函数时使用默认参数的时候,如果默认参数是变量的话,需要注意一下坑。 

     1 # This Python file uses the following encoding: utf-8
     2 
     3 def add_end(l = []):
     4     l.append('end')
     5     print(id(l), l)
     6 
     7 if __name__ == '__main__':
     8     add_end()
     9     add_end()
    10 
    11 输出:
    12 2510338155080 ['end']
    13 2510338155080 ['end', 'end']

    当函数被定义的时候,默认参数"l"就已经被计算出来了,指向地址为2510338155080的list"[]",无论被调用多少次,这个函数的默认参数

    都是指向的这个地址。如果这地址放的是一个变量,那么这个函数被定义过后,这默认参数的值可能会发生变化,代码规范提示原文:

    Default argument value is mutable

    This inspection detects when a mutable value as list or dictionary is detected in a default value for an argument.

    Default argument values are evaluated only once at function definition time,which means that modifying the default value of the argument will affect all subsequent

    calls of the function.

    所以刚才的代码可以优化成这样:

    # This Python file uses the following encoding: utf-8
    
    def add_end(l = None):
        print(id(l))
        if l is None:
            l = []
            l.append('end')
        print(id(l), l)
    
    if __name__ == '__main__':
        add_end()
        add_end()
    
    输出:
    140734702120160
    2314661225032 ['end']
    140734702120160
    2314661225032 ['end']

    参数组合:

    在Python中定义函数,可以用位置参数、默认参数、可变参数、关键字参数和命名关键字参数,这5种参数都可以组合使用。

    但是请注意,参数定义的顺序必须是:位置参数、默认参数、可变参数、命名关键字参数和关键字参数。

    例:

    def f1(a, b, c=0, *args, **kw):
        print('a =', a, 'b =', b, 'c =', c, 'args =', args, 'kw =', kw)
    
    def f2(a, b, c=0, *, d, **kw):
        print('a =', a, 'b =', b, 'c =', c, 'd =', d, 'kw =', kw)
  • 相关阅读:
    搜狗输入法赏析
    第二次冲刺个人总结05
    程序员的自我修养阅读笔记01
    第十五周学习总结
    mysql 查询优化
    mysql explain 详解
    nginx基本配置与参数说明
    input输入框实现联想关键词功能
    JS图片懒加载
    mysql中timestamp,datetime,int类型的区别与优劣
  • 原文地址:https://www.cnblogs.com/renxchen/p/9816660.html
Copyright © 2011-2022 走看看