[Tutor] Confused about __setitem__

Alan Gauld alan.gauld at btinternet.com
Thu Dec 4 09:54:46 CET 2008


"Jim Hodgen" <jhodgen at asymmetricsupplychain.com> wrote

> Why can't I fill the dictionary-as-a-matrix with an instance of 
> class
> Square?

You can but you are not trying to do that in your code.
You are assigning Square to the class that contains the
dictionary, not the dictionary itself.

> class Square:
>     mined = True              # False if empty, True if mined, no 
> other
>     marked = 0                # False if 0, marked-as-mined if 1,
>     displaystate = 0         # covered if 0, marked if 1, exposed if 
> 2,
>     minedneighbors = 0  # number of mined neighboring squares, max 
> legit

These are all class level variables so they will be shared if you
create more than one instance of the class. That's probably
not what you want?. You should initialise them inside an __init__
method if you want each square to have its own values.

> class Baseboard:
>    boardsquares = {}   # dictionary used to emulate an addressable 2

boardsquares is the dictionary not Baseboard

> def initializeboard(xdim, ydim, minenum):
>    gameboard = Baseboard()
>    for yct in range(ydim):
>        for xct in range(xdim):
>            gameboard[(xct,yct)] = Square()

So this needs to be

gameboard.boardsquares[(xct,yct)] = Square()

HTH,

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld 




More information about the Tutor mailing list