首页 > 其他 > 详细

函数传参时,默认参数为变量容易出现的问题

时间:2018-10-19 15:35:19      阅读:487      评论:0      收藏:0      [点我收藏+]

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

 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]

 

函数传参时,默认参数为变量容易出现的问题

原文:https://www.cnblogs.com/renxchen/p/9816660.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!