2017-09-13 92 views
-1

我试图做一个井字游戏,所以我建立了董事会,其中比赛将是,但我得到这个错误:实例方法提高AttributeError的,即使属性被定义

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

回答

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在这种情况下)被调用,这,巧合的是什么也不做实例没有属性。

+0

非常感谢,它非常有帮助。 –

相关问题