-1

我以为我理解了python的传递引用处理......为什么列表的传递引用与列表元素的传递引用之间存在差异,特别是据我所知,如果两者都是对象:

 dataBloc = [ ['123'] , ['345'] ]

 print dataBloc

 def func( b ):
     print ( 'Row-by-Row Before' , b )
     for row in b:
         row = [ float(x) for x in row ]
     print ( 'Row-by-Row After' , b )

     print ( 'Element-by-Element Before' , b )
     for row in b:
         for i in range(len(row)):
             row[i] = float(row[i])
     print ( 'Element-by-Element After' , b )

     return b

 print func(dataBloc)

 [['123'], ['345']]
 ('Row-by-Row Before', [['123'], ['345']])
 ('Row-by-Row After', [['123'], ['345']])
 ('Element-by-Element Before', [['123'], ['345']])
 ('Element-by-Element After', [[123.0], [345.0]])
 [[123.0], [345.0]]

谢谢。

4

3 回答 3

2

首先,这个问题与按值传递或按引用传递无关,因为您没有进行任何传递,您只是在函数中改变值。

其次,没有这样的区别。不同之处在于您的代码:您正在做不同的事情。在第一个循环中,您将列表中的每个元素分配给名称“行”。然后,您重新分配名称“行”以指向其他内容。之前在“行”中的实际值没有改变,所以当然原始列表本身也没有改变,因为你实际上并没有改变内容。

第二,在每一行中,您通过其索引专门改变每个元素的内容。因此,列表发生了变化。

于 2013-09-05T17:21:46.443 回答
0

I thought I understood python's pass-by-reference processing... Why is there a difference between pass-by-reference for lists vs. that for list elements, specially if both are objects as far as I understand it:

Python is call-by-value, not call-by-reference. See the wikipedia page on evaluation strategies.

As @ShashankGupta summarises: "Python is basically considered pass-by-value where all the values are references (since every name in a namespace is just a pointer to some object)." The view that python has some magical other evaluation strategy is the view of small subset of the python community who want python to be magical and unique. Python's way of dealing with objects+call-by-reference isn't even unique, and is present in (at least) Java, Smalltalk, and Ruby.

Also, your code does not show any calling/passing except passing databloc.

于 2013-09-05T17:23:11.553 回答
-1

There is no pass-by-reference or pass-by-value in Python (apart from implementation details – I'm talking about language properties). This kind of categorization just does not apply to Python at all. All there is are objects, who have type, identity (the hash) and data (a value).

The only difference between objects is if their data is mutable or immutable. I recommend reading the official documentation about Python's data model

于 2013-09-05T17:22:33.137 回答