[Tutor] Tutor Digest, Vol 104, Issue 60

Alan Gauld alan.gauld at btinternet.com
Tue Oct 16 11:30:54 CEST 2012


On 16/10/12 08:53, Osemeka Osuagwu wrote:

>> # or make this a regular instance method
>> class Grid:
>>       def extend_grid(self, thickness=4, force=False):
>>           # do stuff to self to extend it
>>           # no need to return anything
>
> Just to clarify, if I went with the top level function; then I guess
> I'll define a 'name' attribute for each individual grid and then pass
> that name in place of the 'grid' argument in your example. Is this
> correct?

Yes but then it wouldn't be OOP. You'd be back in the world of 
traditional procedural programming passing explicit data references 
around. Its much better to make it an instance method with the self 
reference being passed implicitly

>>>           def edit_cell(self, cells, state = '##'):
>>>                   cells = cells
>>>                   for eachcell in cells:
>>>                           Grid.__array[eachcell[0]][eachcell[1]] = state
>>>                   return
>>...
>> As you have written this, you cannot have two Grids. Actually you can, but
>> since they both share the same state, you cannot have two DIFFERENT Grids.
>
> I don't quite get this one; I intended state to be just the value of
> the particular cell in the concerned instance. I don't think it gets
> shared by all the grids.

Notice the line:

Grid.__array[....] = state

The array is shared by all instances because its an attribute of the 
class not the instance. You want every instance to have its own 
__array[] of cells.  ie. self.__array[]

Incidentally the cells = cells line is pointless, it does nothing.


-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/



More information about the Tutor mailing list