python pass parameter as reference
Автор: CodeMore
Загружено: 2023-12-23
Просмотров: 0
Описание:
Download this code from https://codegive.com
In Python, function arguments are typically passed by object reference. This means that when you pass a variable to a function, you are passing a reference to the object it points to, rather than the actual value. This can lead to some interesting behavior, especially when dealing with mutable and immutable objects. In this tutorial, we'll explore how parameter passing works in Python and provide examples to illustrate the concepts.
Passing Immutable Objects
Passing Mutable Objects
Modifying Objects Inside Functions
Immutable objects in Python include integers, floats, strings, and tuples. When you pass these objects to a function, you cannot modify the original value outside the function.
Output:
In this example, the value of num remains unchanged outside the function, even though the function modifies the parameter x.
Output:
Similarly, the original string greeting remains unchanged outside the function.
Mutable objects in Python include lists, dictionaries, and user-defined classes. When you pass these objects to a function, changes made inside the function are reflected outside as well.
Output:
Here, the list my_list is modified both inside and outside the function.
Output:
Similarly, modifications to the dictionary inside the function are reflected outside as well.
To modify immutable objects, you need to explicitly return the modified value and assign it outside the function.
Output:
In this example, the modified list is returned from the function and assigned back to my_list.
ChatGPT
Повторяем попытку...
Доступные форматы для скачивания:
Скачать видео
-
Информация по загрузке: