[Tutor] How to access an instance variable of a superclass from an instance of the subclass?
boB Stepp
robertvstepp at gmail.com
Wed Feb 22 23:25:58 EST 2017
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 only way I have been able to access an
attribute aa of class A is to make aa a class variable. Then I
succeed:
py3: class A:
... aa = 'class A'
...
py3: class B(A):
... def __init__(self):
... self.b = 'class B'
...
py3: a = A()
py3: b = B()
py3: b.aa
'class A'
Obviously I am horribly misunderstanding something, and being
currently sleepy is not helping my cause.
Help, please?
--
boB
More information about the Tutor
mailing list