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

Duncan Smith buzzard at urubu.freeserve.co.uk
Mon Aug 23 22:10:16 EDT 2004


"Porky Pig Jr" <porky_pig_jr at my-deja.com> wrote in message
news:56cfb0e3.0408231710.27d78703 at posting.google.com...
> 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
> ...
>
> What I don't understand: we take the 'data' input (a list), and copy
> it to semi-private instance attribute _data. Something like this:
>
> >>> mystack = Stack([1,2,3])
> >>> dir(mystack)
> ['__doc__', '__init__', '__module__', '_data', 'pop', 'push']
> >>> mystack._data
> [1, 2, 3]
>
> So: why defitions of self.push and self.pop are defined as
> 'data.append' rather than '_data.append', etc. What makes me yet more
> confused: the whole thing works just fine, and yet I can't figure out
> in which attribute we store the results of pushes and where pops are
> coming from.
> Like I push '4' on a stack:
>
> >>> mystack.push(4)
>
> and yet this does not affect _data (obviously):
> >>> mystack._data
> [1, 2, 3]
>
> and yet '4' is stored *somewhere*, since pop() produces the right
> result:
>
> >>> mystack.pop()
> 4
> >>>
>
> Where is that hidden instance attribute and how can I access it? Seems
> like very simple definition, and yet there is something tricky about
> it.
>
> TIA.

>>> alist = [1,2,3]
>>> mystack = Stack(alist)
>>> mystack.push(4)
>>> mystack._data
[1, 2, 3]
>>> alist
[1, 2, 3, 4]

Duncan





More information about the Python-list mailing list