简体   繁体   English

错误:尝试从 class 继承时出现“x 实例没有属性 y”

[英]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.我真的不明白我做错了什么,因为当我以“小规模”尝试它并且它在那里工作时。

I have a class named Play()我有一个名为Play()的 class

I goes like this:我是这样的:

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()然后我有另一个名为Score()的 class

class Score(Play):
    def __init__(self):
        self.initialScore = 0

    def letterGuess(self):
        self.initialScore += 1
        return self.errList

... ...

I instantiated both:我实例化了两者:

game = Play()
points = Score()

And if I do:如果我这样做:

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]

I'm very new to OOP so I could be doing all kinds of silly mistakes but I can't figure out where!我对 OOP 很陌生,所以我可能会犯各种愚蠢的错误,但我不知道在哪里!

I think I have posted all the relevant code, but I you think the error might be elsewhere, I can provide it.我已经发布了所有相关代码,但我认为错误可能在其他地方,我可以提供。

As I said I'm very new, so this might have nothing to do with inheritance I just think it called that when you get "something" from within another class (you must be shouting at the screen by now)正如我所说,我很新,所以这可能与 inheritance 无关

You overwrite the original __init__ , which is then never called and doesn't initialize the members.您覆盖原始的__init__ ,然后它永远不会被调用并且不会初始化成员。 You must call the parent's __init__ separately, usually with this snippet:您必须单独调用父级的__init__ ,通常使用以下代码段:

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

See the docs for super() for details.有关详细信息,请参阅super()的文档 However, super() only works for so-called new-style classes.然而, super()只适用于所谓的新式类。 You must therefore either change the definition of Play to inherit from object :因此,您必须更改Play的定义以从object继承:

class Play(object)

or you call the parent's method directly:或者你直接调用父母的方法:

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

When you inherit from the class Play , you automatically get the attributes that you've created in the definition of Play , but you don't get the attributes that you've created in Play.__init__ .当您从 class Play继承时,您会自动获得在Play定义中创建的属性,但不会获得在Play.__init__中创建的属性。 You have to explicitly call it like so:您必须像这样显式调用它:

class Score(Play):
    def __init__(self):
        Play.__init__(self)
        self.initialScore = 0

See Boldewyn's suggestion for using super to do this;请参阅Boldewyn关于使用super执行此操作的建议; but IMO you should probably get used to the basic way inheritance works before fiddling with super .但是 IMO 在摆弄super之前,您可能应该习惯 inheritance 的基本工作方式。

To further clarify, if you don't override __init__ as you have in this case, then it's inherited and called automatically.为了进一步澄清,如果您没有像在这种情况下那样覆盖__init__ ,那么它会被继承并自动调用。

You forgot to initialize the superclass.你忘了初始化超类。

class Score(Play):
  def __init__(self):
    super(Score, self).__init__()
    self.initialScore = 0

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 类实例没有属性,在Flask中调用函数时出错 - Class instance has no attribute, error when calling a function in Flask 尝试将面数据分离为x和y坐标,但出现错误““ MultiPolygon”对象没有属性“ exterior”” - Trying to separate polygon data into x and y coordinates but get error “ 'MultiPolygon' object has no attribute 'exterior'” 为什么我在尝试从条目 object: Tkinter AttributeError: CustomClass instance has no attribute 'entry' 获取文本时收到此错误? - Why am I getting this error when trying to get text from an entry object: Tkinter AttributeError: CustomClass instance has no attribute 'entry'? 另一个“ X对象没有属性Y”错误 - Yet another “X object has no attribute Y” error QGIS插件中“另存为”错误“ X”对象没有属性“ Y” - Save As error 'X' object has no attribute 'Y' in QGIS plugin 当我从Python中继承实例而不是类时会发生什么? - What happens when I inherit from an instance instead of a class in Python? 类没有属性X. - Class has no attribute X Class 'x' 没有 'y' 成员 - Class 'x' has no 'y' member 将类用于OAuthHandler时发生Tweepy错误:AttributeError:身份验证实例没有属性&#39;apply_auth&#39; - Tweepy error when using class for OAuthHandler: AttributeError: Authentication instance has no attribute 'apply_auth' AttributeError:Rectangle实例没有属性“ y” - AttributeError: Rectangle instance has no attribute 'y'
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM