简体   繁体   中英

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM