官术网_书友最值得收藏!

  • 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.

Figure 4.11:  Referring to the same list in and out of a function

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.

主站蜘蛛池模板: 壤塘县| 卢湾区| 隆安县| 广饶县| 修文县| 响水县| 五大连池市| 虎林市| 浦城县| 新兴县| 宝应县| 秀山| 石家庄市| 海原县| 浏阳市| 台湾省| 迁安市| 牙克石市| 古丈县| 镇康县| 泽库县| 松滋市| 丰台区| 沙湾县| 米易县| 保山市| 肇东市| 香港 | 府谷县| 驻马店市| 马龙县| 苍山县| 龙门县| 义乌市| 涿州市| 岑溪市| 屯门区| 长沙市| 莎车县| 忻州市| 合作市|