[Tutor] super constructor usage
Mats Wichmann
mats at wichmann.us
Thu Mar 30 18:57:41 EDT 2017
On 03/30/2017 05:39 AM, Rafael Knuth wrote:
>>>> I am trying to wrap my head around the super constructor.
>
> Is it possible to embed a super constructor into an if / elif
> statement within the child class?
>
> if message == "string A": return X
> elif: return Y
>
> How should I modify my code below?
> (I couldn't solve that by myself)
>
> class A:
> def __init__(self, message):
> self.message = message
> print(message)
>
> class B(A):
> def __init__(self, message):
> print("This is the message from your parent class A:")
> super(B, self).__init__(message)
>
> B("BlaBla")
For grins, try this (decorated with prints). There's an additional
argument allowed to the class B initializer, but set as a default
argument so that if you omit it it defaults to True.
===
class A(object):
def __init__(self, msg):
print('A: Initializing instance of', self.__class__.__name__)
self.message = msg
class B(A):
def __init__(self, msg, doinit=True):
print('B: Initializing instance of', self.__class__.__name__)
if doinit:
super().__init__(msg)
print("Instantiating an A:")
a = A("some message")
print(a.message)
print("Instantiating a B:")
b = B("some message")
print(b.message)
print("Instantiating a B without calling superclass __init__:")
c = B("some message", False)
print(c.message)
===
When you run it:
Instantiating an A:
A: Initializing instance of A
some message
Instantiating a B:
B: Initializing instance of B
A: Initializing instance of B
some message
Instantiating a B without calling superclass __init__:
B: Initializing instance of B
Traceback (most recent call last):
File "constr-tutor.py", line 22, in <module>
print(c.message)
AttributeError: 'B' object has no attribute 'message'
===
So note that: the instance attribute "message" is set in the class A
initializer, as in all your postings in this thread. Just like Alan
pointed out, there are implications if you don't call up to the
superclass, and it shows up pretty clearly here: in the third case,
where we decide not to call the parent's __init__, this initialization
doesn't happen and the attribute is missing, so accessing it blows up
with an AttributeError exception.
More information about the Tutor
mailing list