Problem with inheritance
Chris Angelico
rosuav at gmail.com
Fri Oct 21 04:34:56 EDT 2011
On Fri, Oct 21, 2011 at 7:07 PM, Sverre <sverreodegard at gmail.com> wrote:
> The line marked with "???" will no be executed and I don't know the
> reason. This example is working as intended, but not not the code I'm
> working on. I'm using Eclipse. I don't know how to debug this
> problem.
>
Did you notice the error you got when you tried? Copying and pasting
your example into IDLE shows this (Python 3):
>>> t=b(1)
Traceback (most recent call last):
File "<pyshell#78>", line 1, in <module>
t=b(1)
File "<pyshell#77>", line 3, in __init__
a.__init__(self,x)
File "<pyshell#76>", line 4, in __init__
self.build()
File "<pyshell#77>", line 8, in build
self.y += 2*self.x
AttributeError: 'b' object has no attribute 'y'
When a calls self.build(), it calls b's build() function. That tries
to modify self.y, which then fails. If you put the self.y = 0 line
above the chaining call to a.__init__, all is well.
Incidentally, you may wish to replace the a.__init__ call with this:
super().__init__(x)
That way, you're not repeating the name 'a', and if you change the
inheritance tree, you don't need to change your code.
ChrisA
More information about the Python-list
mailing list