When passing a variable to a function in Python, the argument is always passed by assignment. This means that the parameter in the function is a reference to the object that is passed in.
However, since Python distinguishes between mutable and immutable types, the behavior of passed variables differs:
Mutable Types:
For mutable types, the passed parameter references the same object that was passed in. Changes made to the object in the function are reflected in the outer scope.
Immutable Types:
For immutable types, the passed parameter is a copy of the object that was passed in. Any changes made to the object in the function are not reflected in the outer scope.
Consider this Python class:
class PassByReference: def __init__(self): self.variable = 'Original' self.change(self.variable) print(self.variable) def change(self, var): var = 'Changed'
When an instance of this class is created:
PassByReference()
The output is 'Original'. This is because the 'var' parameter in the 'change' method is a copy of the 'variable' attribute in the outer scope. Therefore, modifying 'var' within the method has no effect on the original 'variable'.
To achieve pass-by-reference behavior for immutable types, techniques like returning a new value or using a wrapper may be employed:
def change_immutable(parameter): new_parameter = 'Changed' return new_parameter result = change_immutable('Original')
In this case, the 'change_immutable' function returns a new value, which is then assigned to the 'result' variable.
class ImmutableWrapper: def __init__(self, value): self.value = value def change_immutable_wrapper(wrapper): wrapper.value = 'Changed' immutable_wrapper = ImmutableWrapper('Original') change_immutable_wrapper(immutable_wrapper) print(immutable_wrapper.value) # Outputs 'Changed'
In this approach, an object wrapper is used to hold the immutable value. Changes made to the wrapper's value are reflected in the outer scope.
The above is the detailed content of How Does Python's Pass-by-Assignment Impact Mutable and Immutable Types?. For more information, please follow other related articles on the PHP Chinese website!