python - 我可以这样理解[Python中的传递值]吗?

标签 python parameter-passing

大家,最近看了一些关于【Python传值】的文章。

这是链接: How do I pass a variable by reference?

但是,如果我能这样理解,我会感到困惑吗?

enter image description here

如你所见:

  1. Outside the method(): the_link refs to the origin list obj

  2. Inside the method():

    • copy a same new refs the_link(_copy) to the origin list obj
    • if there is a change_refs statement.
    • then Python creates a new list obj inside the method.
    • finally, it let the_list(_copy) refs to this new list obj.
  3. back to Outside: the_link still refs to the origin list obj

如果我这样想的话。 OUTPUT 结果也是一样的。

但我不确定这是OK还是NOT

抱歉,如果我没有正确表达它。希望大家理解==

最佳答案

你没看错。在 Python 中,参数通过所谓的引用值 传递,这意味着引用的副本或值(如果您有 C 语言背景,则为指针)被传递给方法。将这些引用/指针视为包含内存中位置索引的整数。

由于“复制”指针(这就是我们从现在开始引用它的方式)指向“原始”指针所指向的对象,我们对“复制”指针所引用的对象所做的任何修改"指针将反射(reflect)在原始对象中,因为“复制”指针所引用的对象 是原始对象。

但是,由于我们有两个不同的引用(整数)指向内存中的同一个对象(original = XYZ location in memorycopy = XYZ location in memory),当整数位置值 copy 本身已更改(即另一个对象分配给 copy ),更改未反射(reflect)在 original 中因为copyoriginal是两个独立的引用/指针。

但是,如果 copy是指向对象指针的指针(C 中的 ObjectType** copy),更改将反射(reflect)在 original 中也是指针/引用。

如果我们有如下程序,

def mutate_list(copy):
    copy = [5, 6, 7, 8]
    print(original, copy)

original = [1, 2, 3, 4]
mutate_list(original)

输出将为 [1, 2, 3, 4] [5, 6, 7, 8]

如果我们改变 mutate_list方法如下:

def mutate_list(copy):
    copy.clear()
    copy.append([5, 6, 7, 8])
    print(original, copy)

输出将是 [5, 6, 7, 8] [5, 6, 7, 8] .

关于python - 我可以这样理解[Python中的传递值]吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37606219/

相关文章:

python - 我对以下代码的理解正确吗?

c++ - 将元素在 std::map 中的位置作为参数传递给被调用函数

jenkins - 如何将参数传递给 Hudson 作业的 shell 命令

python - 无法使用 cx_Freeze 进行编译

python - 在 Python 列表中查找子字符串

python - **(双星/星号)和*(星号/星号)对参数有什么作用?

powershell - 如何在命令行上传递一系列值-将表达式作为参数传递

python - 一个函数打印 Python 中具有不同参数集的多个函数的返回值

python - 为什么这个父类setter调用使用type(self)而不是self?

python - 如何打包python程序及其依赖包?