错误:英寸×实例没有属性Y'QUOT;试图从类继承时 [英] Error: "x instance has no attribute y" when trying to inherit from class
问题描述
我真的不能明白我在做什么错了,因为当我尝试在小规模,它是在那里工作。
I can't really understand what I'm doing wrong, since when I try it in "small scale" and it is working there.
我有一个名为 A类播放()
我是这样的:
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
...
然后,我有另一种称为类分数()
Then I have another class called 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()
它给了我一个错误:
It gives me an error:
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'
我不明白为什么,因为我可以做到这一点没有任何问题:
I don't understand why since I can do this without any trouble:
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,所以我可以做各种愚蠢的错误,但我想不通的地方!
I'm very new to OOP so I could be doing all kinds of silly mistakes but I can't figure out where!
我觉得我已经发布的所有相关code,但我觉得你的错误可能是在其他地方,我可以提供。
I think I have posted all the relevant code, but I you think the error might be elsewhere, I can provide it.
正如我所说的,我很新,所以这可能什么都没有做继承我只是觉得它称那当你从另一个类中的东西(你必须在屏幕现在喊)
推荐答案
您覆盖原来的 __的init __
,然后永远不会调用和不初始化成员。你必须调用父的 __ __的init
分开,通常在这个片段:
You overwrite the original __init__
, which is then never called and doesn't initialize the members. You must call the parent's __init__
separately, usually with this snippet:
def __init__(self):
super(Score, self).__init__()
请参阅 超()
了解详情。然而,超()
仅适用于所谓的新样式类。因此,必须要么改变的定义播放
从对象继承
:
See the docs for super()
for details. However, super()
only works for so-called new-style classes. You must therefore either change the definition of Play
to inherit from object
:
class Play(object)
或者你直接调用父类的方法:
or you call the parent's method directly:
def __init__(self):
Play.__init__(self)
这篇关于错误:英寸×实例没有属性Y'QUOT;试图从类继承时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!