[Tutor] How to do call by reference (or equiv.) in Py?
alan.gauld@bt.com
alan.gauld@bt.com
Mon Nov 25 19:26:14 2002
I'll just add a few comments to Danny's excellent response...
> >>> x = 42 # x refers to a number object valued 42
> >>> y = x # y refers to the same object (but not to x itself!)
This is like C pointers to int as Danny shows further in his post.
> The key here is that arithmetic in Python (or any manipulation on an
> "immutable" data type), does not modify the object, though:
> it dynamically constructs new objects:
>
> ###
> >>> x = x + 1
So Danny is saying that x now refers to a new number object with the
value of the old number object(which still exists) plus 1 - ie 43
> >>> x
> 43
While y still points at the original number object
> >>> y
> 42
> Lists, on the other hand, are mutable, and index assignment
> does behave just like the arrays that you're used to in C:
As are dictionaries abd, most crucially objects instantiated
from classes. Thus if you define a class, instanciate it and
then pass it into a function and that function modifies the
object the oroginal object will be changed:
class C:
def __init__(s,v): s.v = v
def change(aC): aC.v = 42
c1 = C(5)
c2 = C(7)
print c1,c2 # 5, 7
change(c1)
print c1,c2 # 42, 7 - so original c1 instance was changed
This is because classes(and uinstances) can be seen as special
types of mutable container(like lists etc) so far as argument
passing is concerned.
Sorry if that was all quite clear from Danny's post, I thought
I'd just try to make some things a wee bit more explicit.
Alan g.
Author of the 'Learning to Program' web site
http://www.freenetpages.co.uk/hp/alan.gauld