参数通过引用传递或不通过Python传递

时间:2014-02-10 16:21:43

标签: python list arguments pass-by-reference

Python是通过引用还是通过值传递函数的参数? 我听说int和chars是按值传递的,但列表和字符串是通过引用传递的。

但是当我写 -

def prepend(element,list):
    list = [element] + list

tryList = [1,2,3]
prepend(0,tryList)
print (tryList)

预期的输出是(假设列表通过引用传递)是: [0,1,2,3]。 但实际输出是:[1,2,3],这表明它是按值传递的。

当我写

时出现了主要的困惑
def appendList(element,l):
    l.append(element)
tryList = [1,2,3]
appendList(0,l)
print (l)

输出为:[1,2,3,0]

4 个答案:

答案 0 :(得分:2)

Python仅 PASS-BY-VALUE

就像Java中的非原语一样,Python中的所有值都是引用,即指向对象的指针。就像在Java中一样,它们按值分配和传递。总是

我的定义是:如果对参数的简单赋值(=)与调用范围中传递的变量的简单赋值(=)具有相同的效果,那么它就是传递 - 参考。如果对参数的简单赋值(=)对调用范围中传递的变量没有影响,那么它是按值传递的。它是Java,Python,Ruby,Scheme,Go,C,JavaScript,Smalltalk和许多其他语言的后者。

答案 1 :(得分:-1)

list = [element] + list创建一个新列表并覆盖原始值,嗯,列表。我没有将元素添加到现有列表中,因此它不会显示引用传递。它相当于:

list2 = [element] + list
list = list2

以下内容通过添加到现有列表而不是创建新列表来演示通过引用传递。

def prepend(element, _list):
    _list.insert(0, element)

_try = [1,2,3]
prepend(0, _try)
print(_try)

更新

如果我添加print语句可以更清楚地显示变量在程序执行时如何变化。 prepend有两个版本,一个用于创建新对象,另一个用于更新现有对象。 id()函数返回对象的唯一标识符(在cpython中,对象的内存地址)。

def prepend_1(element, _list):
    print 'prepend_1 creates a new list, assigns it to _list and forgets the original'
    print '_list refers to the same object as _try -->', id(_list), _list
    _list = [element] + _list
    print '_list now refers to a different object -->', id(_list), _list

def prepend_2(element, _list):
    print 'prepend_2 updates the existing list'
    print '_list refers to the same object as _try -->', id(_list), _list
    _list.insert(0, element)
    print '_list still refers to the same object as _try -->', id(_list), _list

_try = [1,2,3]
print '_try is assigned -->', id(_try), _try
prepend_1(0, _try)
print '_try is the same object and is not updated -->', id(_try), _try
prepend_2(0, _try)
print '_try is the same object and is updated -->', id(_try), _try
print _try

当我运行它时,您可以看到对象如何与引用它们的变量相关联

_try is assigned --> 18234472 [1, 2, 3]
prepend_1 creates a new list, assigns it to _list and forgets the original
_list refers to the same object as _try --> 18234472 [1, 2, 3]
_list now refers to --> 18372440 [0, 1, 2, 3]
_try is the same object and is not updated --> 18234472 [1, 2, 3]
prepend_2 updates the existing list
_list refers to the same object as _try --> 18234472 [1, 2, 3]
_list still refers to the same object as _try --> 18234472 [0, 1, 2, 3]
_try is the same object and is updated --> 18234472 [0, 1, 2, 3]
[0, 1, 2, 3]

答案 2 :(得分:-2)

“按对象调用” 这应该回答你的问题。 http://effbot.org/zone/call-by-object.html

答案 3 :(得分:-3)

它不是通过价值。 python中的所有内容都是通过引用传递的。

def prepend(element,list):
    list = [element] + list  # Here new memory is allocated for "list" ,
                              # note list is here a local variable. 

请不要使用'list'作为varible的名称,它是数据类型名称的关键字。

相关问题