猿问

了解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数组等),是否有任何快速的经验法则可以识别哪些参数将通过引用传递,哪些参数将通过值传递?


暮色呼如
浏览 485回答 3
3回答

慕姐8265434

Python中的数字,字符串和元组是不可变的。使用扩展分配将重新绑定名称。您的其他类型仅是mutated,并保持相同的对象。
随时随地看视频慕课网APP

相关分类

Python
我要回答