Python 即使已定义属性,实例方法也会引发AttributeError
我正在尝试做一个井字游戏,所以我正在构建游戏将要进行的板,但我得到了以下错误:Python 即使已定义属性,实例方法也会引发AttributeError,python,class,tic-tac-toe,attributeerror,Python,Class,Tic Tac Toe,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 需要 def __init__(self): 请注意double\uuu,
Traceback (most recent call last):
File "python", line 18, in <module>
File "python", line 10, in display
AttributeError: 'Board' object has no attribute 'cells
需要
def __init__(self):
请注意double\uuu
,否则它将永远不会被调用
例如,以这个类为例,使用
\u init\u
函数
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!
打印某物的事实意味着调用了\uuuuu init\uuuu
请注意,如果类没有
\uuuuu init\uuuuuu
方法,则调用超类“\uuuuuuu init\uuuuu
(在本例中为object
),该超类同时不执行任何操作,也不实例化任何属性。非常感谢,这非常有用。
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!