Python: How do I pass a variable by reference?
- by David Sykes
The Python documentation seems unclear about whether parameters are passed by reference or value, and the following code produces the unchanged value 'Original'
class PassByReference:
def __init__(self):
self.variable = 'Original'
self.Change(self.variable)
print self.variable
def Change(self, var):
var = 'Changed'
Is there something I can do to pass the variable by actual reference?
Update:
I am coming to the conclusion that while Andrea answered my actual question (Can you... No but you can...), on the subject of pass by reference Blair Conrad is more technically correct.
As I understand it the crux is that a copy of a reference is being passed. If you assign that copy, as in my example, then you lose the reference to the original and it remains unchanged. If, however, you 'use' that reference, for example append on a passed list, then the original is changed.
I will see how the comments and votes go before choosing the answer people think is the best