01 Nov, 2009, Confuto wrote in the 1st comment:
Votes: 0
I think I found a solution to this a while ago, promptly forgot it and now can't remember where I found it. In any case, here's the issue:
>>> class A:
def __init__(self):
self.v1 = 1
self.v2 = 2


>>> class B(A):
def __init__(self):
self.v2 = 4
self.v3 = 3


>>> c = B()
>>> c.v3
3
>>> c.v2
4
>>> c.v1

Traceback (most recent call last):
File "<pyshell#84>", line 1, in <module>
c.v1
AttributeError: B instance has no attribute 'v1'
>>>

I can see why this is happening - B's init is overwriting A's completely. Is there a convenient way around this, so that I can leave v1 untouched in B while overwriting v2 and adding v3?

EDIT: Typo :(
01 Nov, 2009, Idealiad wrote in the 2nd comment:
Votes: 0
I think you want something like this:

class A(object):
def __init__(self):
self.v1 = 1
self.v2 = 2


class B(A):
def __init__(self):
super(B, self).__init__()
self.v2 = 4
self.v3 = 3

c = B()
print c.v3, c.v2, c.v1

>C:\Python25\pythonw -u "testClass.py"
3 4 1
>Exit code: 0


Note that you need to explicitly declare A as a child of objectfor super() to work correctly.
01 Nov, 2009, Orrin wrote in the 3rd comment:
Votes: 0
What about:
>>> class A(object):
… def __init__(self):
… self.v1 = 1
… self.v2 = 2

>>> class B(A):
… def __init__(self):
… super(B, self).__init__()
… self.v2 = 4
… self.v3 = 3

>>> c = B()
>>> c.v3
3
>>> c.v2
4
>>> c.v1
1
>>>


Edit: Ninja'd!
02 Nov, 2009, Confuto wrote in the 4th comment:
Votes: 0
Perfect! Thank you both.
0.0/4