Welcome to our Python tutorial series! 🐍 Python primarily uses a mechanism known as "call by object reference" or "call by assignment". This can be a bit confusing because it's different from the traditional "call by value" and "call by reference" used in some other programming languages. Let's clarify how it works in Python:
1. Call by Object Reference (Default Behavior):
In Python, when you pass a variable to a function, you are passing a reference to the object that variable points to, not the actual object itself. This means that if you modify the object inside the function, the changes are reflected outside the function as well. However, if you reassign the variable inside the function, it will not affect the variable in the calling scope.
2. Call by Value (Simulating in Python):
Although Python primarily uses "call by object reference," you can simulate "call by value" by passing immutable objects like integers, strings, or tuples. Since these objects cannot be modified, any change made inside the function creates a new object, which doesn't affect the original variable.
3. Call by Reference (Not Natively Supported):
True "call by reference" is not natively supported in Python. However, you can achieve similar behavior by passing mutable objects like lists or dictionaries and modifying them inside the function. Changes made to mutable objects are reflected outside the function.
immutable: call by value (copy)
mutable: call by reference (exact)
def inc(tup, lst, dct):
tup += (99,)
lst.append(999)
dct["val9999"] = 9999
print("*** inside function ***")
print(tup)
print(lst)
print(dct)
print("******")
tup = (1, 2, 3)
lst = [11, 22, 33]
dct = {
"val1" : 111,
"val2" : 222,
"val3" : 333
}
print("*** before ***")
print(tup)
print(lst)
print(dct)
print("******")
inc(tup, lst, dct)
print("*** after inc executed ***")
print(tup)
print(lst)
print(dct)
print("******")
Output:
** before **
(1, 2, 3)
[11, 22, 33]
{'val1': 111, 'val2': 222, 'val3': 333}
******
** inside function **
(1, 2, 3, 99)
[11, 22, 33, 999]
{'val1': 111, 'val2': 222, 'val3': 333, 'val9999': 9999}
******
** after inc executed **
(1, 2, 3)
[11, 22, 33, 999]
{'val1': 111, 'val2': 222, 'val3': 333, 'val9999': 9999}
******
In summary, Python primarily uses "call by object reference," but the behavior depends on whether the object is mutable or immutable. You can achieve behavior similar to "call by value" or "call by reference" by choosing appropriate data types and understanding how changes to objects are managed.
Don't forget to like, share, and subscribe for more Python tutorials and coding insights! 🔔
#PythonProgramming #PythonFunctions #PythonTutorial #CodingTips #callbyvalue #callbyreference
Информация по комментариям в разработке