开发者

parameters : passed by reference vs passed by name

开发者 https://www.devze.com 2023-03-04 13:19 出处:网络
what is the difference between the parameter passing modes passed by reference and passed by name here is an example in Python but suppose we don\'t use any Python rules:

what is the difference between the parameter passing modes passed by reference and passed by name here is an example in Python but suppose we don't use any Python rules:

def P(x,y)
   global i
   y=1
   print(x)
   i=2
   print(x,y)
i=0
a = [7,11,13]
P(a[i],i)
P(i,a[i])

so here passing parameters by reference would give the output:

  • 7
  • 7, 2
  • 2
  • 2, 1

I am sorry in advance if there is any mistake.

passing by name says that we just apply a textual substitution but I am still confused about how to get outputs using call by name. Any help?

here is what I got using passing by name:

  • 7
  • 11, 2
  • 2
  • 2, 1

is it corre开发者_如何学Pythonct?


In Python you have objects that are either mutable or immutable. All names are references to an object. In other words, everything is a reference. You don't "pass by value" in Python. There is only pass by reference. If you try to modify an immutable object (e.g. number or string), you get a new copy automatically. You can return that new value. If you pass a mutable object (e.g. list or dict) the object is modified, you don't have to return it. If you don't want that you should copy your object first. You can use dict.copy() or list[:] syntax for that.


They're almost the same. But sometimes they work different. Here's an example.

Effect of the call swap (x, y):
  temp := x;
  x := y;
  y := temp
Effect of the call swap (i, x[i]):
  temp := i;
  i := x[i];
  x[i] := temp
It does not work! For example:
Before call: i = 2, x[2] = 5
After call: i = 5, x[2] = 5, x[5] = 2

There's a detailed description here scope-binding-papameter-passing-techniques. Check this charpter "Parameter Passing Techniques" and you'll find your answer.


I'm not sure if this is what you were asking for, but I can explain the difference between call-by-reference and call-by-name. If you call a function with a parameter by reference, any modification to that variable will change it in the function that called it. As an example, if the following function got x by reference:

def foo(x):
    x = x+1

def main():
    x = 5
    foo(x)
    print x

This would print 6. If you had called it by name, it would print 5 instead.

Does that make sense?

0

精彩评论

暂无评论...
验证码 换一张
取 消