[Tutor] super constructor usage
Mats Wichmann
mats at wichmann.us
Wed Mar 29 19:01:17 EDT 2017
On 03/29/2017 04:02 PM, Mats Wichmann wrote:
> 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.
etc.
To make sure there's an even simpler answer than poring through all
those cases (which I think is useful), also try this minimal rewrite of
your example:
class A(object):
def __init__(self, message):
self.message = message + " (decorated by superclass)"
class B(A):
def __init__(self, message):
print("Class B initializer called with %s argument" % message)
super().__init__(message)
b = B("BlaBla")
print("instance message =", b.message)
More information about the Tutor
mailing list