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 ?
5 Réponses
+ 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/
+ 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
+ 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
+ 2
Vitaly Sokol
Yup, whoops - fixed thanks