12.07.2015 Views

Is Python a

Is Python a

Is Python a

SHOW MORE
SHOW LESS
  • No tags were found...

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

<strong>Python</strong>’s pass-by-assignment scheme isn’t quite the same as C++’s reference parametersoption, but it turns out to be very similar to the C language’s argument-passingmodel in practice:• Immutable arguments are passed “by value.” Objects such as integers andstrings are passed by object reference instead of by copying, but because youcan’t change immutable objects in-place anyhow, the effect is much like makinga copy.• Mutable arguments are passed “by pointer.” Objects such as lists and dictionariesare also passed by object reference, which is similar to the way C passesarrays as pointers—mutable objects can be changed in-place in the function,much like C arrays.Of course, if you’ve never used C, <strong>Python</strong>’s argument-passing mode will seem simplerstill—it just involves the assignment of objects to names, and it works the samewhether the objects are mutable or not.Arguments and Shared ReferencesHere’s an example that illustrates some of these properties at work:>>> def changer(a, b): # Function... a = 2 # Changes local name's value only... b[0] = 'spam' # Changes shared object in-place...>>> X = 1>>> L = [1, 2] # Caller>>> changer(X, L) # Pass immutable and mutable objects>>> X, L # X is unchanged, L is different(1, ['spam', 2])In this code, the changer function assigns values to argument a, and to a componentin the object referenced by argument b. The two assignments within the function areonly slightly different in syntax, but have radically different results:• Because a is a local name in the function’s scope, the first assignment has noeffect on the caller—it simply changes the local variable a, and does not changethe binding of the name X in the caller.• b is a local name, too, but it is passed a mutable object (the list called L in thecaller). As the second assignment is an in-place object change, the result of theassignment to b[0] in the function impacts the value of L after the functionreturns. Really, we aren’t changing b, we are changing part of the object that bcurrently references, and this change impacts the caller.Passing Arguments | 327

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!