python工匠系列(深入理解列表可变性)

###理解列表的可变性###

#示例一 :为字符串追加内容——————类似值传递(pass—by—value)

print('类似值传递')

def add_str(in_func_obj):
    print(f'In add [before] : in_func_obj="{in_func_obj}"')
    in_func_obj += 'suffix'
    print(f'In add [after]  :  in_func_obj="{in_func_obj}"')

orig_obj='foo'
print(f'Outside [before]:   orig_obj="{orig_obj}"')
add_str(orig_obj)
print(f'Outside [after]  :    orig_obj="{orig_obj}"')


"""
输出
Outside [before]:   orig_obj="foo"
In add [before] : in_func_obj="foo"
In add [after]  :  in_func_obj="foosuffix"
Outside [after]  :    orig_obj="foo"
"""
print('*************************************************')
#示例二:为列表追加内容(与上面的代码逻辑一致,但是吧字符串换成列表)——————引用传递(pass—by—reference)

print('类似引用传递')

def add_str(in_func_obj):
    print(f'In add [before] : in_func_obj="{in_func_obj}"')
    in_func_obj += ['baz']
    print(f'In add [after]  :  in_func_obj="{in_func_obj}"')

orig_obj=['foo','bar']
print(f'Outside [before]:   orig_obj="{orig_obj}"')
add_str(orig_obj)
print(f'Outside [after]  :    orig_obj="{orig_obj}"')

"""
输出
Outside [before]:   orig_obj="['foo', 'bar']"
In add [before] : in_func_obj="['foo', 'bar']"
In add [after]  :  in_func_obj="['foo', 'bar', 'baz']"
Outside [after]  :    orig_obj="['foo', 'bar', 'baz']"
"""


"""
********************************************************************************************************************
python 在进行函数调用传参时,采用的既不是值传递,也不是引用传递,而是传递了‘变量所指对象的引用’(pass-by-ogbjedt-reference)
所以,当我们在函数内部执行in_func_obj += ...等修改操作时,是否会影响外部变量,只取决于in_func_obj所指向的的对象是否可变
********************************************************************************************************************
"""

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值