在定义函数时使用默认参数的时候,如果默认参数是变量的话,需要注意一下坑。
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
时间: 2024-10-06 11:54:47