大家,最近看了一些关于【Python传值】的文章。
这是链接: How do I pass a variable by reference?
但是,如果我能这样理解,我会感到困惑吗?
如你所见:
Outside the method(): the_link refs to the origin list obj
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.
back to Outside: the_link still refs to the origin list obj
如果我这样想的话。 OUTPUT 结果也是一样的。
但我不确定这是OK还是NOT?
抱歉,如果我没有正确表达它。希望大家理解==
最佳答案
你没看错。在 Python 中,参数通过所谓的引用值 传递,这意味着引用的副本或值(如果您有 C 语言背景,则为指针)被传递给方法。将这些引用/指针视为包含内存中位置索引的整数。
由于“复制”指针(这就是我们从现在开始引用它的方式)指向“原始”指针所指向的对象,我们对“复制”指针所引用的对象所做的任何修改"指针将反射(reflect)在原始对象中,因为“复制”指针所引用的对象 是原始对象。
但是,由于我们有两个不同的引用(整数)指向内存中的同一个对象(original = XYZ location in memory
和 copy = XYZ location in memory
),当整数 或位置值 copy
本身已更改(即另一个对象分配给 copy
),更改未反射(reflect)在 original
中因为copy
和 original
是两个独立的引用/指针。
但是,如果 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/