-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.

1
  • You need to call it self.puzzle in __init__ as well. This is not magic. Commented Aug 14, 2017 at 3:26

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

4 Comments

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 Exactly. It isn't "like" this, it is this. Cheers.
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 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).

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.