[Tutor] super constructor usage

Mats Wichmann mats at wichmann.us
Wed Mar 29 18:02:16 EDT 2017


On 03/29/2017 08:33 AM, Rafael Knuth wrote:

> class A:
>     def __init__(self, message):
>         self.message = message
>         print(message)
> 
> I then modified the child class B like this:
> 
> class B(A):
>     def __init__(self, message):
>         print("This is the message from your parent class A:")
>         super(B, self).__init__(message)
> 
> B("BlaBla")
> 
> That works, however I am not sure about what exactly happens inside the code.
> What I am concerned about is whether the argument is being actually
> inherited from the parent class A or does B overwrite the argument.
> Can anyone advise what the correct solution would be (in case mine is wrong).
> Thank you.

Alan (as usual) already sorted this.

Just to try to fill in some of these questions - what's inherited,
overridden, etc., I'm pasting a bit of code I wrote for somewhere else
to demonstrate what's going on.  Hope it provides some enlightenment
(it's written for Python3, you'd have to change the super() call if
you're using Python2).

Note that your print(message) in A's initializer doesn't really tell you
much, it just tells you what argument was passed to the initializer.
That would be the same for any function/method, and tells you nothing
about inheritance.

class A(object):
    print('Setting class variables in A')
    aa_cls = 'class A data'

    def __init__(self):
        print('A: Initializing instance of', self.__class__.__name__)
        self.aa = 'instance of class A'

    def ameth(self):
        return "A method from class A"

class B(A):
    print('Setting class variables in B')
    bb_cls = 'class B data'

    def __init__(self):
        print('B: Initializing instance of', self.__class__.__name__)
        super().__init__()
        self.bb = 'instance of class B'

print("Begin examination...")
print("Data from classes:")
print("A.aa_cls:", A.aa_cls)
print("B.aa_cls:", B.aa_cls)

print("Instantiating A as a:")
a = A()
print("Instantiating B as b:")
b = B()

print("Data from instance a:")
print("a.aa_cls:", a.aa_cls)
print("a.aa:", a.aa)
print("call ameth directly from a:", a.ameth())
print("Dict a:", a.__dict__)

print("Data from instance b:")
print("b.bb_cls:", b.bb_cls)
print("b.bb:", b.bb)
print("b.aa_cls:", b.aa_cls)
print("call ameth from b:", b.ameth())
print("b.aa:", b.aa)
print("Dict b:", b.__dict__)



More information about the Tutor mailing list