I wrote this class for testing:
class PassByReference:
def __init__(self):
self.variable = 'Original'
self.change(self.variable)
print(self.variable)
def change(self, var):
var = 'Changed'
When I created an instance, the output was “Original.” So, it seems like parameters in Python are passed by value. Is that correct? How can I modify the code to achieve the effect of Python pass-by reference so that the output is “Changed”?
Since Python passes immutable types (like strings) by value, you can use a mutable object, such as a list or dictionary, to simulate passing by reference.
Here’s an example using a list:
class PassByReference:
def __init__(self):
self.variable = ['Original'] # Use a list (mutable)
self.change(self.variable)
print(self.variable[0]) # Access the first element
def change(self, var):
var[0] = 'Changed' # Modify the list's content
In this solution, the list variable is mutable, so when it’s passed to change, the changes affect the original list. This is an example of a Python pass-by reference with a mutable object.
Another way to simulate Python pass by reference is by using a dictionary, which is also mutable:
class PassByReference:
def __init__(self):
self.variable = {'value': 'Original'} # Use a dictionary (mutable)
self.change(self.variable)
print(self.variable['value']) # Access the dictionary value
def change(self, var):
var['value'] = 'Changed' # Modify the dictionary's value
With this solution, the dictionary’s value can be modified inside the change method, and the change is reflected in the original object.
You can create a custom object that holds the value and pass that object to simulate Python pass-by reference:
class PassByReference:
def __init__(self):
self.variable = MyVariable('Original') # Pass a custom object
self.change(self.variable)
print(self.variable.value) # Access the object's attribute
def change(self, var):
var.value = 'Changed' # Modify the attribute of the object
class MyVariable:
def __init__(self, value):
self.value = value
Here, MyVariable is a custom class with an attribute value. When the variable object is passed to change, its value attribute can be modified directly, simulating Python pass-by reference.