0
How to pass by reference in Python?
I just discovered that there are no ways to pass a var by reference in Python. From what I've seen this does not even exist in this language, which sounds strange to me, because I'm used to languages derived from C, such as C# or C++, for example. The question is, if this does not actually exist in Python, how can I get the same result?
4 Réponses
+ 2
strawdog
Technically, yes, but you cannot assign to them in the function body:
def x(y):
x = 2 # here, x becomes a local variable inside the function
a = 1
print(a) # 1
x(a)
print(a) # still 1
You can still mutate mutable structures, like lists, though:
def x(y):
y.append(2)
a = [1]
print(a) # [1]
x(a)
print(a) # [1, 2]
Anyway, essentially, passing by reference is limited and can't be controlled by the programmer. Mutable objects (lists, dicts, class objects, etc.) can be used as a reference, but immutable objects cannot, and reassigning anything makes it a local variable (excluding **kwargs, that's a topic for another day). I think the purpose of this was to make the language easier to understand, and have only one way of doing things, a Python philosophy.
+ 2
Better answer than I could write: https://stackoverflow.com/questions/986006/how-do-i-pass-a-variable-by-reference
+ 1
The point is that in Python every var IS a reference.
>>> var = "a variable"
>>> def checkid(x):
print(id(x))
print(id(var))
>>> id(var)
48941960
>>> checkid(var)
48941960
48941960
>>>
+ 1
Thank you guys!