python常见问题与陷阱

可变默认参数

def append_to(element, to=[]):
    to.append(element)
    return to
print(append_to(111))
print(append_to(222))
print(append_to(333))

# 实际输出
[111]
[111, 222]
[111, 222, 333]

因为在定义函数的时候,就创建了一个可变对象list, 后续所有操作都是在这一个对象中进行的(dict也不行)

# 正确写法
def append_to(element, to=None):
	if to == None:
    	to = []
    to.append(element)
    return to
开发工具 文章被收录于专栏

包含常用开发工具: 1. git 2. Docker 3. xshell 4. ...

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务