-1

the code of my program is here: Why am I getting this error "NameError:name 'self' is not defined."

The error I get is the following:

Traceback (most recent call last):
  File "sudoku_maker.py", line 51, in <module>
    p.main()
  File "sudoku_maker.py", line 44, in main
    self.createEasy()
  File "sudoku_maker.py", line 16, in createEasy
    if (self.puzzle[i][j] != 0):
AttributeError: 'Puzzle' object has no attribute 'puzzle'

The only reason I could see why this error is happening is because the list is only declared in the init function but I put it in there because I saw another answer on here that said to do it that way. I was gonna comment on the answer saying asking how to do that for class variable but I didn't have enough rep and then I found another question where the answerer said to only declare a list in the init function.

cs95
  • 379,657
  • 97
  • 704
  • 746
codehelp4
  • 132
  • 1
  • 2
  • 15

1 Answers1

0

Why haven't you initialised puzzle as an instance variable? As it is, it is only a local variable. You'll need:

def __init__(self, **puzzle): 
    self.puzzle = [[0 for x in range(9)]for y in range(9)]

self is your instance, and self.x = ... will result in x, an instance variable, and is accessible as an attribute of self.

cs95
  • 379,657
  • 97
  • 704
  • 746
  • because I didn't realize that that's how you have to write it now I think I finally fully get it. "self" is the python equivalent of the keyword "this" in a way. I wish other answer I saw about questions involving class variables explained that. – codehelp4 Aug 14 '17 at 03:43
  • @codehelp4 Exactly. It isn't "like" `this`, it _is_ `this`. Cheers. – cs95 Aug 14 '17 at 03:44
  • Having said that it still surprises me that you have to write it that what since it's the first time it's being declared. Needless to say thanks again. – codehelp4 Aug 14 '17 at 04:01
  • @codehelp4 You don't want to declare a local variable and have it assigned as an attribute variable against your will, right? Remember, explicit is always better than implicit (Zen of Python). – cs95 Aug 14 '17 at 04:02