2017-09-13 49 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

非常感謝,它非常有幫助。 –

相關問題