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

Robert Brewer fumanchu at amor.org
Tue Aug 24 03:46:19 CEST 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
> ... 
> 
> 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.

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



More information about the Python-list mailing list