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

我不确定我是通过传递函数参数的对象样式来理解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 dictionary

tnumber = 1

print id( tnumber ), tnumber

ttuple  = (1, 2, 3)

print id( ttuple ) , ttuple

tlist   = [1, 2, 3]

print id( tlist ) , tlist

tdict = tel = {'jack': 4098, 'sape': 4139}

print '-------'

# Invoke a function and test it

foo(tnumber, ttuple, tlist , tdict)

print '-------'

#Test behaviour after the function call is over

print id(tnumber) , tnumber

print id(ttuple)  , ttuple

print id(tlist)   , tlist

print id(tdict),  tdict

该程序的输出是

146739376 1

3075201660 (1, 2, 3)

3075103916 [1, 2, 3]

3075193004 {'sape': 4139, 'jack': 4098}

---------

146739364 2

3075201660 (1, 2, 3)

3075103916 [1, 2, 3, 3.4]

3075193004 {'sape': 4139, 'jack': 4098, 'mary': 2.3}

---------

146739376 1

3075201660 (1, 2, 3)

3075103916 [1, 2, 3, 3.4]

3075193004 {'sape': 4139, 'jack': 4098, 'mary': 2.3}

如您所见,除了传递的整数外,对象ID(据我所知指的是内存位置)保持不变。

因此,对于整数,它(有效地)通过值传递,而其他数据结构(有效地)通过引用传递。我尝试更改列表,数字和字典,以仅测试数据结构是否已就位。列表中没有数字,字典中没有数字。

我在上面有效地使用了这个词,因为参数传递的“按对象调用”样式似乎根据上述代码中传递的数据结构表现出两种方式

对于更复杂的数据结构(例如numpy数组等),是否有任何快速的经验法则可以识别哪些参数将通过引用传递,哪些参数将通过值传递?

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值