[Tutor] How to access an instance variable of a superclass from an instance of the subclass?

boB Stepp robertvstepp at gmail.com
Thu Feb 23 22:01:34 EST 2017


Thank you to everyone that provided illumination in this thread!
Things seem much clearer now, which caused me to realize that what I
wrote below cannot work as written (Even though I did copy and paste
it from the interpreter):

On Wed, Feb 22, 2017 at 10:53 PM, boB Stepp <robertvstepp at gmail.com> 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...
>
> I have partially answered my own question, but I am not sure I
> understand the mechanics yet.  Apparently I must explicitly assign
> class A's attribute, aa, to an instance of class B as follows:
>
> py3: class B(A):
> ...     def __init__(self):
> ...             self.aa = super().aa
> ...             self.bb = 'class B'
> ...
> py3: b = B()
> py3: b.aa
> 'class A'

If I had copied and pasted the above two sections of code
*contiguously*, this should have resulted in:

py3: class B(A):
...     def __init__(self):
...             self.aa = super().aa
...             self.bb = 'class B'
...
py3: b = B()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 3, in __init__
AttributeError: 'super' object has no attribute 'aa'
py3: a = A()
py3: b = B()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 3, in __init__
AttributeError: 'super' object has no attribute 'aa'

When I went back to scroll back in ConEmu (Thanks Eryk Sun for
bringing this program to my attention!), I found that I had redefined
class A as follows:

py3: class A:
...     aa = 'class A'
...

between those two blocks of code, which explains why "b = B()"
followed by "b.aa" worked.

Sorry 'bout that!  I did mention I was sleepy at the time... ~(:>))

-- 
boB


More information about the Tutor mailing list