问题描述
||
我无法真正理解自己在做什么错,因为当我以“小规模”尝试时,它就可以正常工作了。
我有一班叫
Play()
我是这样的:
class Play():
def __init__(self):
file = open(\"/home/trufa/Desktop/test\",\"r\")
self.word = random.choice(file.readlines()).rstrip()
self.errAllowed = 7
self.errMade = 0
self.errList = []
self.cheatsAllowed = 2##chetas not incrementing
self.cheatsMade =0
self.wordList = [\"*\"]*len(self.word) ##this one is the one I want to have available in another class
...
然后我还有另一堂课score()
class score(Play):
def __init__(self):
self.initialscore = 0
def letterGuess(self):
self.initialscore += 1
return self.errList
...
我都实例化了:
game = Play()
points = score()
如果我这样做:
print points.letterGuess()
它给我一个错误:
Traceback (most recent call last):
File \"/home/trufa/workspace/hangpy/src/v2.py\",line 188,in <module>
startGame()
File \"/home/trufa/workspace/hangpy/src/v2.py\",line 134,in startGame
print points.letterGuess()
File \"/home/trufa/workspace/hangpy/src/v2.py\",line 79,in letterGuess
return self.errList
AttributeError: score instance has no attribute \'errList\'
我不明白为什么,因为我可以轻松完成此操作:
class One():
def __init__(self):
self.list= [1,2]
class Two(One):
def meth(self):
return self.list
uan = One()
tu = Two()
print uan.list
print tu.meth() ## Both output [1,2]
我是OOP的新手,所以我可能会犯各种愚蠢的错误,但我不知道该在哪里!
我想我已经发布了所有相关代码,但是我认为错误可能在其他地方,我可以提供。
正如我说的我很新,所以这可能与继承无关,我只是以为它是在您从另一个类中获得“某些东西”时调用的(现在您必须在屏幕上大喊大叫)
解决方法
您将覆盖原始的“ 8”,然后将其永不调用并且不初始化成员。通常,必须使用以下代码片段分别调用父母的ѭ8:
def __init__(self):
super(Score,self).__init__()
有关详细信息,请参阅文档中的ѭ11。但是,“ 11”仅适用于所谓的新型类。因此,您必须更改Play
的定义以继承object
:
class Play(object)
或者您直接调用父级的方法:
def __init__(self):
Play.__init__(self)
,当您从类Play
继承时,您会自动获得在Play
定义中创建的属性,但不会获得在Play.__init__
中创建的属性。您必须像这样明确地调用它:
class Score(Play):
def __init__(self):
Play.__init__(self)
self.initialScore = 0
请参阅Boldewyn的关于使用using21ѭ的建议。但是IMO可能在您熟悉super
之前应该已经习惯了继承的基本方式。
为了进一步说明,如果您不像在这种情况下那样覆盖__init__
,那么它将被继承并自动调用。
,您忘记了初始化超类。
class Score(Play):
def __init__(self):
super(Score,self).__init__()
self.initialScore = 0