Binding new objects in a function

Let's look at another instructive example. First, we'll create a new list f:

>>> f = [14, 23, 37]

Then we'll create new a function replace(). As the name suggests, rather than modifying its arguments replace() will change the object that its parameter refers to:

>>> def replace(g):
... g = [17, 28, 45]
... print("g =", g)
...

We now call replace() with actual argument f:

>>> replace(f)
g = [17, 28, 45]

This is much as we'd expect. But what's the value of the external reference f
now?

>>> f
[14, 23, 37]

The object reference f still refers to the original, unmodified list. This time, the function did not modify the object that was passed in. What's going on?

The answer is this: The object reference f was assigned to the formal argument named g, so g and f did indeed refer to the same object, just as in the previous example:

Figure 4.12 :  Initially 'f' and 'g' refer to the same list object

However, on the first line the of the function we re-assigned the reference g to point to a newly constructed list [17, 28, 45], so within the function the reference to the original [14, 23, 37] list was overwritten, although the unmodified object itself was still pointed to by the f reference outside the function:

Figure 4.13 :  After reassignment, 'f' and 'g' refer to different objects
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset