newbie: confused with example in Learning Python 2nd Edition:cananyone give a hint
Paul McGuire
ptmcg at austin.rr._bogus_.com
Mon Aug 23 22:09:41 EDT 2004
"Paul McGuire" <ptmcg at austin.rr._bogus_.com> wrote in message
news:RdxWc.15249$v86.14245 at fe2.texas.rr.com...
> "Robert Brewer" <fumanchu at amor.org> wrote in message
> news:mailman.2254.1093312305.5135.python-list at python.org...
> Porky Pig Jr wrote:
> <snip>
>
> Hint: Python doesn't have variables like other languages do. The line:
>
> self._data = list(data)
>
> does not make a copy of "data". Instead, it binds a new name
> (self._data) to the same object which the name "data" refers to.
>
>
> FuManChu
> ======================
>
> Er? I thought list(data) called the list constructor to create a copy of
> data, and bind the new list to self._data. That's why push and pop calls
> update the internal _data list without changing the original list.
>
> -- Paul
>
>
Well, this *is* a screwy example, and I question why this twisted thing is
in a beginner text. I'm not even sure I really like the style anyway.
Here is the original Stack class posted by the OP:
>>> class Stack:
... def __init__(self, data):
... self._data = list(data)
... self.push = data.append
... self.pop = data.pop
...
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]
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:
>>> s = Stack(baselist)
>>> baselist
[1, 2, 3, 4]
>>> s.pop()
4
>>> baselist
[1, 2, 3, 4]
>>> s._data
[1, 2, 3]
HTH,
-- Paul
More information about the Python-list
mailing list