Search code examples
pythonclasstic-tac-toeattributeerror

Instance method raises AttributeError even though the attribute is defined


I'm trying to make a tic tac toe game so I'm building the board where the game will be on, but I'm getting this errors:

Traceback (most recent call last):
  File "python", line 18, in <module>
  File "python", line 10, in display
AttributeError: 'Board' object has no attribute 'cells

Can't figured out the cause of the problem

import os #try to import the clode to the operating system, use import 
os.system('clear')

# first: Build the board
class Board():  #use class as a templete to create the object, in this case the board
    def _init_(self):
      self.cells = [' ', ' ', ' ' , ' ', ' ', ' ' , ' ', ' ', ' '] #will use self to define the method, in this case the board cells
    def display(self):
      print ('%s   | %s | %s' %(self.cells[1] , self.cells[2] , self.cells[3]))
      print ('_________')
      print ('%s   | %s | %s' %(self.cells[4] , self.cells[5] , self.cells[6]))
      print ('_________')
      print ('%s   | %s | %s' %(self.cells[7] , self.cells[8] , self.cells[9]))
      print ('_________')


board = Board ()
board.display ()

Solution

  • def _init_(self):
    

    Needs to be

    def __init__(self):
    

    Note the double __, otherwise it is never invoked.


    As an example, take this class with an _init_ function.

    In [41]: class Foo:
        ...:     def _init_(self):
        ...:         print('init!')
        ...:         
    
    In [42]: x = Foo()
    

    Note that nothing is printed out. Now consider:

    In [43]: class Foo:
        ...:     def __init__(self):
        ...:         print('init!')
        ...:         
    
    In [44]: x = Foo()
    init!
    

    The fact that something is printed means __init__ was invoked.

    Note that if class does not have an __init__ method, the superclass' __init__ (object in this case) is invoked, which, coincidentally does nothing and instantiates no attributes.