- The Python Apprentice
- Robert Smallshire Austin Bingham
- 253字
- 2021-07-02 22:17:05
Modifying external objects in a function
To demonstrate Python's argument passing semantics, we'll define a function at the REPL which appends a value to a list and prints the modified list. First we'll create a list and give it the name m:
>>> m = [9, 15, 24]
Then we'll define a function modify() which appends to, and prints, the list passed to it. The function accepts a single formal argument named k:
>>> def modify(k):
... k.append(39)
... print("k =", k)
...
We then call modify(), passing our list m as the actual argument:
>>> modify(m)
k = [9, 15, 24, 39]
This indeed prints the modified list with four elements. But what does our list reference m outside the function now refer to?
>>> m
[9, 15, 24, 39]
The list referred to by m has been modified because it is the self-same list referred to by k inside the function. As we mentioned at the beginning of the section, when we pass an object-reference to a function we're essentially assigning from the actual argument reference, in this case m, to the formal argument reference, in this case k.

As we have seen, assignment causes the assigned-to reference to refer to the same object as the assigned-from reference. This is exactly what's going on here. If you want a function to modify a copy of an object, it's the responsibility of the function to do the copying.
- 手機安全和可信應用開發指南:TrustZone與OP-TEE技術詳解
- C語言程序設計案例教程
- 微信公眾平臺與小程序開發:從零搭建整套系統
- PyTorch自動駕駛視覺感知算法實戰
- Learning RxJava
- Arduino開發實戰指南:LabVIEW卷
- JavaScript 網頁編程從入門到精通 (清華社"視頻大講堂"大系·網絡開發視頻大講堂)
- 深入淺出Serverless:技術原理與應用實踐
- Microsoft Dynamics AX 2012 R3 Financial Management
- 新印象:解構UI界面設計
- Hacking Android
- Angular Design Patterns
- Joomla!Search Engine Optimization
- Java 9:Building Robust Modular Applications
- 跟小樓老師學用Axure RP 9:玩轉產品原型設計