I have a nested list, named env, created in the constructor and another method to populate an element of the grid defined as below:
class Environment(object):
def __init__(self,rowCount,columnCount):
env = [[ None for i in range(columnCount)] for j in range(rowCount) ]
return env
def addElement(self, row, column):
self[row][column] = 0
Later in the code I create an instance of Environment by running:
myEnv = createEnvironment(6,6)
Then I want to add an element to the environment by running:
myEnv.addElement(2,2)
So what I expected to happen was that I would receive a new Environment object as a 6×6 grid with a 0 in position 2,2 of the grid. But that did not work.
I have two errors:
- I am unable to return anything other than None from the init method.
-
The main issue us when trying to execute
addElement(2, 2)I get this error:"TypeError: 'Environment' object does not support indexing.
I looked at the __getitem__ and __setitem__ methods but was unable to get them working over a multidimensional list. Is there a better data structure I should be using to create a grid?
The problem here is that you can’t replace the object with
__init__. You could subclasslistand do something in__new__, probably, but that would be massive overkill, the better option is just to wrap the list:Note that it’s a little odd you claim to be calling
myEnv = createEnvironment(6,6)– using a function rather than the constructor is a little odd.If you really want your object to act like the list, you can of course provide a load of extra wrapper functions like
__getitem__/__setitem__. E.g:Which would allow you to do
some_environment[5, 6], for example. (You may rather return the column, that depends on your system and what works best for you).