Python 容器的可变性 - 一道题

def add_to(num, target=[]):
    target.append(num)
    return target print add_to(1)  print add_to(2)  print add_to(3)
  输出非常的怪异,[1],[1,2],[1,2,3],并不是我们想象中的 [1] ,[2],[3]
点解???
这是列表的可变性在作怪。在Python中当函数被定义时,默认参数只会运算一次,而不是每次被调用时都会重新运算。你应该永远不要定义可变类型的默认参数,除非你知道你正在做什么。
你应该像这样做:
  
def add_to(element, target=None):
    if target is None: target = [] target.append(element) return target
  
 

猜你喜欢

转载自www.cnblogs.com/muyiblog/p/9204630.html
今日推荐