newbie: confused with example in Learning Python 2nd Edition:cananyone give a hint

Porky Pig Jr porky_pig_jr at my-deja.com
Tue Aug 24 08:40:35 CEST 2004


> As it turns out, this stack does not even need the assignment statement to
> self._data at all.  Here is a fuller console example:
> 
> >>> class Stack:
> ...         def __init__(self, data):
> ...             self.push = data.append
> ...             self.pop = data.pop
> ...
> >>> s = Stack([1,2,3])
> >>>
> >>> s.push(4)
> >>> s.pop()
> 4
> 
> Where did the 4 get pushed to/popped from?!  This Stack class doesn't have
> *any* member variable to store the list contents!
> 
> In fact, the stack is stored in the input list - in this case, the temporary
> list literal [1,2,3].  This is a bit clearer if we pass in a variable
> instead of a literal list:
> 
> >>> baselist = [1,2,3]
> >>> s = Stack(baselist)
> >>> s.push(4)
> >>> baselist
> [1, 2, 3, 4]
> 

Thanks. I've started suspecting at some point that _data is a red
herring, and the real action takes place in the 'data', list passed as
a parameter, but didn't think of something that simple as assigning it
to a variable, so I can display it.

> I can't say I'm thrilled about this class that silently takes ownership of
> the input list.  I suspect that the book example has a typo, and that the
> class should really read:
> 
> >>> class Stack:
> ...         def __init__(self, data):
> ...             self._data = list(data)
> ...             self.push = self._data.append
> ...             self.pop = self._data.pop
> 
> Now things are better behaved:
> 

Yes, I did make this change, but then everything is simple, clear, no
mistery at all. I was curious about the original one - the way it's
given in a textbook.

May be I'll send a feedback with a pointer to this thread. Incidently,
I really like this book in general. Seems like this is the only one
reallhy screwy example.

Thanks again.



More information about the Python-list mailing list