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

Instance method raises AttributeError even though the attribute is defined

我正在尝试制作一个井字游戏,所以我正在构建游戏将要运行的棋盘,但我遇到了以下错误:

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 ()
def _init_(self):

需要

def __init__(self):

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


例如,使用 class 和 _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__ 已被调用。

请注意,如果 class 没有 __init__ 方法,则会调用 superclass' __init__(本例中为 object),巧合的是,它什么也不做,也没有实例化任何属性。