python - 这怎么能叫引用传递呢?

标签 python pass-by-reference terminology pass-by-value

根据 this教程中,Python 使用“按引用传递”。

然后他们继续给出以下示例。这个“引用传递”是在哪个星球上?对我来说,这看起来像是一个明确的“按值传递”案例。

想法?

def changeme( mylist ):
   mylist = [1,2,3,4];
   print "Values inside the function: ", mylist
   return

mylist = [10,20,30];
changeme( mylist );
print "Values outside the function: ", mylist

The parameter mylist is local to the function changeme. Changing mylist within the function does not affect mylist. The function accomplishes nothing and finally this would produce the following result:

# Values inside the function:  [1, 2, 3, 4]
# Values outside the function:  [10, 20, 30]

更新,结论:

  1. 根据下面 viraptor 的回答,“根据文档,python 是按值传递的”。所以教程显然是错误的。

  2. Python 不是“引用调用”,而是“共享调用”。这意味着可以将引用传递给局部子例程,由子例程更新,并且更新保留在子例程的本地,不会自动影响引用的全局值。

最佳答案

两者都不是。是call by sharing .我还听说过“按引用值传递”一词。

Also known as "call by object" or "call by object-sharing," call by sharing is an evaluation strategy first named by Barbara Liskov et al. for the language CLU in 1974. It is used by languages such as Python, Iota, Java (for object references), Ruby, JavaScript, Scheme, OCaml, AppleScript, and many others. However, the term "call by sharing" is not in common use; the terminology is inconsistent across different sources. For example, in the Java community, they say that Java is call-by-value, whereas in the Ruby community, they say that Ruby is call-by-reference, even though the two languages exhibit the same semantics. Call by sharing implies that values in the language are based on objects rather than primitive types, i.e. that all values are "boxed".

The semantics of call by sharing differ from call by reference in that assignments to function arguments within the function aren't visible to the caller (unlike by reference semantics), so e.g. if a variable was passed, it is not possible to simulate an assignment on that variable in the caller's scope. However, since the function has access to the same object as the caller (no copy is made), mutations to those objects, if the objects are mutable, within the function are visible to the caller, which may appear to differ from call by value semantics. Mutations of a mutable object within the function are visible to the caller because the object is not copied or cloned — it is shared.

关于python - 这怎么能叫引用传递呢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36852971/

相关文章:

python - 如何让 Aquamacs 在 ipython 中运行代码

c++ - 编译错误 : expected ‘)’ before ‘&’ token

java - Java是“按引用传递”还是“按值传递”?

terminology - C# 和 Visual C#?

python - 凯撒密码只返回第一个翻译的字母?

python - 如何测试一个对象是否是锁?

python - 如何在 Python 中使用原始套接字?

c++ - 返回一个对象:值,指针和引用

java - Java中RTTI和反射的区别

computer-science - 老年人计算机科学