gpt4 book ai didi

python - 错误 : "x instance has no attribute y" when trying to inherit from class

转载 作者:太空狗 更新时间:2023-10-30 00:23:44 25 4
gpt4 key购买 nike

我真的不明白我做错了什么,因为当我在“小规模”中尝试它并且它在那里工作时。

我有一个名为 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 的新手,所以我可能会犯各种愚蠢的错误,但我不知道在哪里!

认为我已经发布了所有相关代码,但我认为错误可能出在其他地方,我可以提供。

正如我所说的,我是新手,所以这可能与继承无关,我只是认为当您从另一个类中获得“某物”时(您现在一定对着屏幕大喊大叫) )

最佳答案

您覆盖了原始的 __init__,它永远不会被调用并且不会初始化成员。您必须单独调用父级的 __init__,通常使用以下代码段:

def __init__(self):
super(Score, self).__init__()

参见 docs for super()了解详情。但是,super() 仅适用于所谓的新型类。因此,您必须更改 Play 的定义以继承自 object:

class Play(object)

或者你直接调用父类的方法:

def __init__(self):
Play.__init__(self)

关于python - 错误 : "x instance has no attribute y" when trying to inherit from class,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6143693/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com