[Tutor] Passing objects

Alan Gauld alan.gauld at blueyonder.co.uk
Thu Jul 8 10:32:10 CEST 2004


> >>> def foo(shape):
> shape = SWFShape()
> return shape
> >>> r = ""
> >>> foo(r)
> <ming.SWFShape instance at 0x00B9CB20>
> >>> r
> ''
> >>>
>
> I am somewhat mystified by the above behaviour. A class instance is
> instantiated, but r remains a string.

Of course. You create the shape inside the function,
after the function finishes the shape is lost. If you want to keep
it you need to assign the function return value to a variable:

>>> r = foo(r)
>>> r
<ming.SWFShape instance at 0x00B9CB20>

> How can I pass an instance of an object to a function, that will
> permit the objects methods applied in the function?

Just pass the object into the function. The function can call the
objects methods. I assume you tried that and had a roblem?

> I was exploring the utility of the following.
>
> def bar(Object):
> Object.MainClassFunction(args)
> return anObject

I assume this should read

 return Object

>
> instance = MainClass()
> bar(instance)
>
> This clearly fails.

No, it should succeed(with the fixed return statement). What happened
that made you think it fails? But notice that once again you throw
away
the result of your function.

HTH,

Alan G
Author of the Learn to Program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld



More information about the Tutor mailing list