[Tutor] How to access an instance variable of a superclass from an instance of the subclass?
Alex Kleider
akleider at sonic.net
Thu Feb 23 00:02:57 EST 2017
On 2017-02-22 20:53, boB Stepp wrote:
> On Wed, Feb 22, 2017 at 10:25 PM, boB Stepp <robertvstepp at gmail.com>
> wrote:
>> I am trying to wrap my head around the mechanics of inheritance in
>> Python 3. I thought that all attributes of a superclass were
>> accessible to an instance of a subclass. But when I try the
>> following:
>>
>> py3: class A:
>> ... def __init__(self):
>> ... self.aa = 'class A'
>> ...
>> py3: class B(A):
>> ... def __init__(self):
>> ... self.bb = 'class B'
>> ...
>> py3: a = A()
>> py3: b = B()
>> py3: b.aa
>> Traceback (most recent call last):
>> File "<stdin>", line 1, in <module>
>> AttributeError: 'B' object has no attribute 'aa'
>>
>> I am unsuccessful...
The 'attribute(s)' to which you refer only exist because of the
__init__s.
B's __init__ over rides that of A so A's __init__ never gets called
during instantiation of b and hence b.aa never comes into being.
More information about the Tutor
mailing list