Tru*_*ufa 5 python inheritance attributes instance
我无法真正理解我做错了什么,因为当我在"小规模"尝试时它正在那里工作.
我有一个名为的班级 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
Run Code Online (Sandbox Code Playgroud)
...
然后我有另一个叫做的课 Score()
class Score(Play):
def __init__(self):
self.initialScore = 0
def letterGuess(self):
self.initialScore += 1
return self.errList
Run Code Online (Sandbox Code Playgroud)
...
我实例化了两个:
game = Play()
points = Score()
Run Code Online (Sandbox Code Playgroud)
如果我这样做:
print points.letterGuess()
Run Code Online (Sandbox Code Playgroud)
它给了我一个错误:
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'
Run Code Online (Sandbox Code Playgroud)
我不明白为什么我可以毫无困难地这样做:
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]
Run Code Online (Sandbox Code Playgroud)
我对OOP很新,所以我可以做各种愚蠢的错误,但我无法弄清楚在哪里!
我想我已经发布了所有相关代码,但我认为错误可能在其他地方,我可以提供.
正如我所说的那样,我很新,所以这可能与继承无关我只是认为当你从另一个类中获得"某些东西"时(你现在必须在屏幕上大喊大叫)
Bol*_*wyn 12
您将覆盖原始内容__init__,然后从不调用原始内容并且不会初始化成员.您必须__init__单独调用父级,通常使用以下代码段:
def __init__(self):
super(Score, self).__init__()
Run Code Online (Sandbox Code Playgroud)
有关详细信息,请参阅文档super().但是,super()仅适用于所谓的新式课程.因此,您必须更改Play要继承的定义object:
class Play(object)
Run Code Online (Sandbox Code Playgroud)
或者直接调用父方法:
def __init__(self):
Play.__init__(self)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
11047 次 |
| 最近记录: |