且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Python:什么时候通过引用传递变量,什么时候通过值传递?

更新时间:2022-06-22 22:29:20

Python 中的一切都是按值传递和赋值的,就像 Java 中的一切都是按值传递和赋值一样.Python 中的每个值都是一个对象的引用(指针).对象不能是值.赋值总是复制值(它是一个指针);因此,两个这样的指针可以指向同一个对象.对象永远不会被复制,除非你做了一些明确的事情来复制它们.

Everything in Python is passed and assigned by value, in the same way that everything is passed and assigned by value in Java. Every value in Python is a reference (pointer) to an object. Objects cannot be values. Assignment always copies the value (which is a pointer); two such pointers can thus point to the same object. Objects are never copied unless you're doing something explicit to copy them.

对于您的情况,循环的每次迭代都会将列表的一个元素分配给变量 loc.然后将其他内容分配给变量 loc.所有这些值都是指针;您正在分配指针;但您不会以任何方式影响任何对象.

For your case, every iteration of the loop assigns an element of the list into the variable loc. You then assign something else to the variable loc. All these values are pointers; you're assigning pointers; but you do not affect any objects in any way.