Totally Confused: Passing variables to functions
Dave Harrison
dave at nullcube.com
Thu Jun 5 04:38:01 EDT 2003
Just as a side mention you might also be in a class,
in which case the 'global' (read class-wide) variable
is accessed as self.variableName
being forced to reference with self is a useful bug stopper
if you want - for some reason - to have a local variable with the same
name as the global variable.
eg. where the global variable arg has been defined as 2
def foo(self, arg):
return arg+self.arg
print 'Global : '+str(self.arg)
self.foo(2)
print 'Local plus Global : '+str(foo)
Michael Mayhew (mayhew at cis.ohio-state.edu):
> Howdy,
>
> To address the first problem, the following sample worked for me:
>
> def blah(arg):
> arg[:] = []
> return arg
>
> I think the reason is that using the slice operation, you are still, as you
> noticed, using methods on the "object reference" and so can change the
> mutable object in place.
>
> For the second example, this sounds like a question of scope as v is
> declared in your global scope, but arg is local to the function. If you
> wanted to change v itself in the function blah, you would write
>
> def blah():
> global v
> v = v + 1
>
> v = 1
> blah()
> Now v equals 2!
>
> If you wanted to simply change the local function reference to v, you would
> have to return the result and assign it to v, like so:
>
> def blah(arg):
> arg = arg+1
> return arg
>
> v = blah(v)
> Now v equals 2!
>
>
> I hope this helps somewhat,
>
> Michael
>
>
>
>
> --
> http://mail.python.org/mailman/listinfo/python-list
More information about the Python-list
mailing list