-2

class Grid:

def __init__(self, row, col, inp):
    self.row = row
    self.col = col
    self.inp = inp
    newGrid = []
    newGrid.append([[0]*col]*row)

def changeGrid(self, row, col, inp):
    newGrid #says it is not defined

Why cant changeGrid() access the variable newGrid?

Barmar
  • 669,327
  • 51
  • 454
  • 560
  • 4
    `newGrid` is a local variable in the `__init__` method. You should use `self.newGrid` to make it an instance variable. – Barmar May 25 '22 at 21:48
  • 3
    Unrelated problem: `[[0]*col]*row` will not do what you want. See https://stackoverflow.com/questions/240178/list-of-lists-changes-reflected-across-sublists-unexpectedly – Barmar May 25 '22 at 21:49

2 Answers2

2

in order to access "newGrid" you need to make it an attribute of the class

try something like this

def __init__(self, row, col, inp):
    self.row = row
    self.col = col
    self.inp = inp
    self.newGrid = []
    self.newGrid.append([[0]*col]*row)

def changeGrid(self, row, col, inp):
    self.newGrid #now you should have access to it 
Ohad Sharet
  • 81
  • 1
  • 5
1

Because newGrid is not reachable in the scope of changeGrid. Depending on what you're trying to achieve you could either make newGrid a class member or an instance member. More detail here Python Class Members