newbie: confused with example in Learning Python 2nd Edition: can anyone give a hint
Steven Rumbalski
srumbalski at copper.net
Mon Aug 23 23:27:18 EDT 2004
Porky Pig Jr wrote:
> Here is an example of Stack class which got me totally confused:
>
>>>> class Stack:
> ... def __init__(self, data):
> ... self._data = list(data)
> ... self.push = data.append
> ... self.pop = data.pop
It should have confused you. It was wrong.
>From the errata at
http://www.oreilly.com/catalog/lpython2/errata/lpython2.confirmed:
{457} class Stack: code;
self.push and self.pop should both reference self._data, not just data
So the corrected code should look like:
>>> class Stack:
... def __init__(self, data):
... self._data = list(data)
... self.push = _data.append
... self.pop = _data.pop
And now the class should act like you expect. Before it was modifying the
list (data) it was passed in the constructor. Now it modifies its own copy
(_data).
By the way, a brief note on errata. IMO it is counter-productive to dwell
on errata (although a quick skim doesn't hurt). Trying to notice each
error distracts from understanding. Usually the brain glosses over the
error and reads what was intended rather than what was said.
More information about the Python-list
mailing list