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 6x6 grid with a 0 in position 2,2 of the grid. But that did not work.

I have two errors:
1) I am unable to return anything other than None from the init method.
2) 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?

Your class should read

class Environment(object):
    def __init__(self,rowCount,columnCount):
        self.env = [[ None for i in range(columnCount)] for j in range(rowCount) ]       

    def setElement(self, row, column, value = 0):
        self.env[row][column] = value

    def getElement(self, row, column):
        return self.env[row][column]

myenv = Environment(6, 6) # create an instance
myenv.setElement(2, 2)
myenv.setElement(3, 4, 1000)

The __init__() method never returns anything. Its role is to initialize an instance created dynamically when you call Environment().

Awesome! Thanks for your help.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.