为了账号安全,请及时绑定邮箱和手机立即绑定

了解Python的传递函数参数的按对象调用样式

了解Python的传递函数参数的按对象调用样式

暮色呼如 2019-10-21 13:12:08
我不确定我是通过传递函数参数的对象样式来理解Python调用的概念的(此处解释为http://effbot.org/zone/call-by-object.htm)。似乎没有足够的例子来很好地阐明这个概念(或者我的google-fu可能很弱!:D)我写了这个人为的Python程序来尝试理解这个概念def foo( itnumber, ittuple,  itlist, itdict   ):    itnumber +=1     print id(itnumber) , itnumber     print id(ittuple)  , ittuple    itlist.append(3.4)    print id(itlist)   , itlist    itdict['mary']  = 2.3    print id(itdict),    itdict# Initialize a number, a tuple, a list and a dictionarytnumber = 1print id( tnumber ), tnumber ttuple  = (1, 2, 3)print id( ttuple ) , ttupletlist   = [1, 2, 3]print id( tlist ) , tlisttdict = tel = {'jack': 4098, 'sape': 4139}print '-------'# Invoke a function and test itfoo(tnumber, ttuple, tlist , tdict)print '-------'#Test behaviour after the function call is overprint id(tnumber) , tnumber print id(ttuple)  , ttupleprint id(tlist)   , tlistprint id(tdict),  tdict该程序的输出是146739376 13075201660 (1, 2, 3)3075103916 [1, 2, 3]3075193004 {'sape': 4139, 'jack': 4098}---------146739364 23075201660 (1, 2, 3)3075103916 [1, 2, 3, 3.4]3075193004 {'sape': 4139, 'jack': 4098, 'mary': 2.3}---------146739376 13075201660 (1, 2, 3)3075103916 [1, 2, 3, 3.4]3075193004 {'sape': 4139, 'jack': 4098, 'mary': 2.3}如您所见,除了传递的整数外,对象ID(据我所知指的是内存位置)保持不变。因此,对于整数,它(有效地)通过值传递,而其他数据结构(有效地)通过引用传递。我尝试更改列表,数字和字典,以仅测试数据结构是否已就位。列表中没有数字,字典中没有数字。我在上面有效地使用了这个词,因为参数传递的“按对象调用”样式似乎根据上述代码中传递的数据结构表现出两种方式对于更复杂的数据结构(例如numpy数组等),是否有任何快速的经验法则可以识别哪些参数将通过引用传递,哪些参数将通过值传递?
查看完整描述

3 回答

?
慕姐8265434

TA贡献1813条经验 获得超2个赞

Python中的数字,字符串和元组是不可变的。使用扩展分配将重新绑定名称。


您的其他类型仅是mutated,并保持相同的对象。


查看完整回答
反对 回复 2019-10-21
  • 3 回答
  • 0 关注
  • 484 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信