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

Steven D'Aprano steve at pearwood.info
Thu Feb 23 04:57:14 EST 2017


On Wed, Feb 22, 2017 at 10:25:58PM -0600, boB Stepp 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'
> ...

There you have a class with an initializer method.

And here you subclass it:

> py3: class B(A):
> ...     def __init__(self):
> ...             self.bb = 'class B'
> ...

But you *override* the initialiser method and prevent the superclass' 
method from running. Only B's custom version will run.

That's allowed, but fairly unusual. Normally you want to "overload" the 
method. Python can't guess if you want to call the superclass' version 
before or after your customization, so you have to decide for yourself:

class B(A):
    def __init__(self):
        super().__init__()  # call the superclass first
        self.bb = 'class B'
        super().__init__()  # or last

(Just don't do it twice, as I have! :-)

In this specific instance, it doesn't matter whether you call super() 
first or last, but often it will.


Welcome to the complexity of inheritence! And wait until you learn about 
multiple-inheritence, diamond diagrams, mixins, traits, and more. 

It's not *always* this complex. Often you subclass just to extend the 
class by adding a new method, and inheritence Just Works. You don't even 
have to think about it. But when overriding and overloading methods, you 
do have to think about what you are doing.



-- 
Steve


More information about the Tutor mailing list