[Tutor] scope question

Poor Yorick gp@pooryorick.com
Wed Jan 15 18:29:01 2003


Norvell Spearman wrote:

>On Wednesday, 2003.01.15, 15:25:26 -0700, Poor Yorick wrote:
>
>
>So the only way to write a modifier (as opposed to a pure function) for
>an object is to change the object's attributes, right?
>
Not sure exactly what you mean.  You can often use the return value of a 
function to modify something.  For example:

 >>> def DoSomething():
    var = 'Darth Vader'

   
 >>> name = 'Poor Yorick'
 >>> def ReturnSomething():
    var = 'Darth Vader'
    return var

 >>> name = 'Poor Yorick'
 >>> print name
Poor Yorick

 >>> name = ReturnSomething()
 >>> print name
Darth Vader
 >>>

>
>
>One more question --- sorry to be a pain, but I want to make sure I
>understand this correctly:  In the following function definition
>
>def foo(bar):
>    ...
>    bar = bam  # bam has attributes x and y, as does parameter bar
>    bar.x = x
>    bar.y = y
>
>``bar = bam'' is a new variable, local to the function and completely
>separate from the passed bar, but ``bar.x = x'' and ``bar.y = y'' will
>affect the parameter bar and not the function-local bar.  Is that
>correct?
>

No, bar and bam are now identifiers for the sam object in memory, and 
that is the only object you are going to be changing.  Within the scope 
of the function, you have effectively lost your handle to the object 
passed in as parameter "bar".

Poor Yorick
gp@pooryorick.com