即使定义了属性,Instance方法也会引发AttributeError

时间:2017-09-13 05:06:41

标签: python class tic-tac-toe attributeerror

我试图制作一个tic tac toe游戏,所以我要构建游戏所在的棋盘,但我收到了这个错误:

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

无法找出问题的原因

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

1 个答案:

答案 0 :(得分:4)

def _init_(self):

需要

def __init__(self):

请注意双__,否则永远不会调用它。

例如,使用_init_函数取此类。

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

In [42]: x = Foo()

请注意,没有打印出任何内容。现在考虑:

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

In [44]: x = Foo()
init!

打印某些内容的事实意味着调用__init__

请注意,如果类没有__init__方法,则会调用超类“__init__(在这种情况下为object”,这恰好一无所获,并且不实例化任何属性。< / p>