传参需要注意的坑

在类或者函数中,都可能涉及到传参的过程,传参方式分为两种:按值传和按引用传

  按值传:传的是内存中保存的内容 (value),参数为不可变的按值传,如:'abc'

  按引用传:传的是内容在内存中保存的地址(id),参数为可变的按引用传,如:list

def func(a=[], b="abc"):
    a.append('hello')
    return a,b

f1 =func(b="word")
print(f1)
f2 =func()
print(f2)

结果:
([
'hello'], 'word') (['hello', 'hello'], 'abc') # 这里就多了一个值

结论:当参数为可变类型时,参数id是一致的,但内容会受到影响,这是我们不愿看到的,对于这种可变的参数类型,我们正确定义方法是:如下面代码所示

 

def func(a=None, b="abc"):
    if not a:
        a = []
    a.append('hello')
    return a,b

f1 =func(b="word")
print(f1)
f2 =func()
print(f2)

结果:

(['hello'], 'word')
(['hello'], 'abc')

 

posted @ 2020-03-19 16:46  海澜时见鲸  阅读(196)  评论(0)    收藏  举报