Pass by reference or by value?
Steve Holden
steve at holdenweb.com
Thu Aug 16 20:34:42 EDT 2007
Robert Dailey wrote:
[but he top-posted, so he should consider himself smacked on the wrist]
> On 8/16/07, *Steve Holden* <steve at holdenweb.com
> <mailto:steve at holdenweb.com>> wrote:
>
> Robert Dailey wrote:
> > So immutable objects cannot be modified directly? I guess this means
> > integers are immutable and the act of assigning to one is a
> completely
> > new definition?
>
> Correct. A new value is bound to the name or item on the left-hand side
> - remember, all variables are pointers to values, there's no way to
> replace the value of a variable because of the automatic dereferencing.
> And yes, immutable objects can't be modified. At all, period. Hence the
> name.
>
> > So if I were to create a class called Integer and
> give
> > it a .set() method, this would allow me to create mutable
> integers, and
> > thus passing in an object of type class Integer would allow me to
> modify
> > the value from inside the function?
> >
> Well, the .set() method wouldn't be called automatically on an
> assignment statement but yes, if you passed an Integer object into your
> function and called its .set() method from inside then it should work.
>
> As long as you get your mutable integer implementation correct, of
> course ;-). I'd suggest delegating everything except the .set() method
> to the underlying integer value.
> Thanks Steve for your explanation. It was very helpful. I think I
> understand it now. By the way, by the .set method I meant:
>
> class Integer:
> def __init__( self, number=0 ):
> self._int = number
>
> def set( self, number ):
> self._int = number
>
>
> # later on....
>
> mutableInt = Integer( 5 )
> def change_me( var ):
> var.set( 6 )
>
>
> Of course, I'd probably use overloaded operators in a more realized
> example.
>
>
Fair enough, but I was trying to point out that assignment isn't an
operator so you won't be able to achieve what you want by assignment to
a name local to the function.
You could, of course, assign to a name local to the instance you passed
in, but then there wouldn't be much point in using anything but a simple
subclass of object (normally referred to as Bunch).
regards
Steve
--
Steve Holden +1 571 484 6266 +1 800 494 3119
Holden Web LLC/Ltd http://www.holdenweb.com
Skype: holdenweb http://del.icio.us/steve.holden
--------------- Asciimercial ------------------
Get on the web: Blog, lens and tag the Internet
Many services currently offer free registration
----------- Thank You for Reading -------------
More information about the Python-list
mailing list