[Tutor] How to access an instance variable of a superclass from an instance of the subclass?
Zachary Ware
zachary.ware+pytut at gmail.com
Wed Feb 22 23:49:37 EST 2017
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.
>
> Obviously I am horribly misunderstanding something, and being
> currently sleepy is not helping my cause.
I'll give you a couple of hints. First, try this:
print('defining A')
class A:
print('Setting a on class A')
a = 'a on class A'
def __init__(self):
print('Setting aa on instance of', self.__class__.__name__)
self.aa = 'aa in A.__init__'
print('defining B')
class B(A):
print('Setting b on class B')
b = 'b on class B'
def __init__(self):
print('Setting bb on instance of', self.__class__.__name__)
self.bb = 'bb in B.__init__'
print('Instantiating a')
a = A()
print('Instantiating b')
b = B()
Next, have a look at
https://docs.python.org/3/library/functions.html#super and in
particular the link at the end to Raymond Hettinger's "super
considered super" essay.
And finally, there's one line you can add to B.__init__ that will get
what you're after.
I hope this is helpful, I'm sure others will be along with in-depth
explanations before long anyway :)
Regards,
--
Zach
More information about the Tutor
mailing list