我不确定我是否理解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数组等),有没有快速的经验法则
识别哪些参数将通过引用传递,哪些参数将通过值传递?