beginner question, function returning object.

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Thu Feb 7 03:36:04 EST 2008


On Thu, 07 Feb 2008 19:14:54 +1100, bambam wrote:

> Second try (correction)
> 
> I started with ths:
>  ------------------------------
> def open_pipe():
>     pipe=PIPE()
>     print pipe
>     return pipe

What's PIPE() do?


> pipe=open_pipe()

(Extraneous space removed.)

> pipe.parent = self.parent

What's self? What's it do? What's self.parent and what does it do?

> print pipe
>  ------------------------------
>  It didn't do what I wanted: when I printed the pipe the second time it
>  was not the same object as the first time.

How do you know? What makes you think they are different objects?


 
>  So I changed it to this:
> def open_pipe(pipe):
>     pipe=PIPE()
>     print pipe
> 
>  pipe = None

Again with the extraneous space.

> open_pipe(pipe)

This can't possibly work. What you are doing is this:

(1)  set the name 'pipe' to None
(2)  call the function open_pipe() with None as the argument
(3)  which reassigns the *inner* variable 'pipe' to the result of PIPE(),
but doesn't do anything to the *global* variable 'pipe'
(4)  open_pipe() now returns None, which doesn't get used

So as you can see, the global 'pipe' starts off as None, and then nothing 
happens to it, so it stays None.

> pipe.parent = self.parent
> print pipe
> 
>  It still doesn't do what I wanted: I can't assign the parent property
>  because pipe type is None.
>
>  I'm not sure enough of what I am doing to tell if I have another error
>  in my
>  code causing the problem. Is either of these examples supposed to work
>  as shown? Is it clear that either example is obviously wrong?


Your first attempt was almost certainly the correct way to try to do what 
you want. I suspect that your function PIPE() is broken.



-- 
Steven



More information about the Python-list mailing list