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

Porky Pig Jr porky_pig_jr at my-deja.com
Mon Aug 23 21:10:36 EDT 2004


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.



More information about the Python-list mailing list