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(据我所知是指memeory位置)保持不变。

所以在整数的情况下,它是(有效地)通过值传递的,而其他数据结构是(有效地)通过引用传递的。我尝试更改列表、数字和字典,以测试数据结构是否已更改到位。号码不在名单上

字典是。

我在上面有效地使用了这个词,因为“按对象调用”的参数传递方式似乎在两种情况下都有不同的行为,这取决于在上面的代码中传递的数据结构

对于更复杂的数据结构(比如numpy数组等),有没有快速的经验法则

识别哪些参数将通过引用传递,哪些参数将通过值传递?

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值