pass parameters by reference ? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

pass parameters by reference ?

def fun(param1,param2): param1 += 10 param2 += 10 a = 10 b = 10 fun(a,b) #prints a = 10 , b = 10 #i want it to be like usual in any other lang #a = 20 and b = 20 also #when one pass by reference . let me rephrase this ... As any one can see this is called pass by value that's what happened here . now how can i turn this into pass by reference ?

29th Sep 2021, 2:14 AM
‎وائل عبد الحق‎
‎وائل عبد الحق‎ - avatar
5 Answers
+ 3
Python isn't exactly a pass by value language, but rather a pass by assignment. It uses namespaces in a hierarchical fashion, in which each namespace has a key, value dictionary like structure to contain its variable names and values. The most common thing to do is to return the value from the function and reassign the new value(s) to the same name(s). def fun(param1, param2): return param1 + 10, param2 + 10 a = 10 b = 10 a, b = fun(a, b) One of the ways in which you can simulate a pass-by-reference function is to wrap the value in an structure object such as a list, dictionary, custom object or namespace and pass it. form types import SimpleNamespace ns = SimpleNamespace() def fun(instance): instance.a += 10 instance.b += 10 ns.a = 10 ns.b = 10 fun(ns) https://realpython.com/python-pass-by-reference/
29th Sep 2021, 2:45 AM
ChaoticDawg
ChaoticDawg - avatar
+ 2
Answer: https://stackoverflow.com/questions/986006/how-do-i-pass-a-variable-by-reference TL/DR: You can't pass them by reference. You can either use a wrapper class to pass them by reference, or use a return statement to return the new value
29th Sep 2021, 2:37 AM
Rishi
Rishi - avatar
+ 2
ChaoticDawg , you must pass an instance of the class to your function, but not the numbers (ns.a, ns.b) as parameters: def fun (self): self.a += 10 self.b += 10 fun(ns) print(ns.a, ns.b) >> 20 20
29th Sep 2021, 4:08 AM
Vitaly Sokol
Vitaly Sokol - avatar
+ 2
Vitaly Sokol Yup, whoops - fixed thanks
29th Sep 2021, 4:18 AM
ChaoticDawg
ChaoticDawg - avatar
29th Sep 2021, 7:14 AM
Vitaly Sokol
Vitaly Sokol - avatar