[Tutor] Passing objects

Gregor Lingl glingl at aon.at
Thu Jul 8 08:48:16 CEST 2004

Alex Newby schrieb:

>Continuing on my quest to understand how to pass around objects with
>>>>def foo(shape):
>	shape = SWFShape()
>	return shape
>>>>r = ""
><ming.SWFShape instance at 0x00B9CB20>
You define a function with 1 parameter: shape.
In Python parameters are local names - so this name
will not exist any more, when foo() is done.

When you call foo(r), shape refers to the empty string.
Interestingly you don't make use of this object now
called shape in the body of foo().
Instead, in the next statement, which is an assignment, this
is changed and shape now refers to the object constructed by
the call SWFShape(). So shape is a name for
this object.

The next statement returns that reference. If you now want
r to be a name for this object, you simply have to write:

r = foo(r)

Alas, you could as well write

r = foo("something") or r = foo(1001) with the same result.

... or redefine foo:

def foo():
    shape = SWFShape()
return shape

and call

r = foo()

foo within its body cannot replace the object r refers to.
It could - in principle - change that object, but
  (1) not by an assignment, which assigns another object to the 
parameter and
  (2) only if that object were mutable - which is not the case for strings.
(But although the concept of mutable and immutable objects is
crucial in Python that's probably beyond the scope of your question)

2 more comments to the following:

>I am somewhat mystified by the above behaviour. A class instance is
>instantiated, but r remains a string. How can I pass an instance of an
>object to a function, that will permit the objects methods applied in
>the function?
>I was exploring the utility of the following.
>def bar(Object):
>	Object.MainClassFunction(args)
>	return anObject
1. here anObject is not a name which refers to something, so a nameErrpr 
will occur

>instance = MainClass()
2. it generally doesn't make much sense to call a function, which returns
something without using this returned object - be it in an assignment 

obj = bar(instance)

or in an expression like 


Regards, Gregor


More information about the Tutor mailing list