Reputation: 101
I know many topics around class inheritance in Python have been addressed, but I could not find a thread that addressed this specific issue.
Edit: I'm running Python 3.5.5.
Code:
class Parent():
def __init__(self, parentParam="parent param"):
self.parentParam = parentParam
class Child(Parent):
def __init__(self, childParam = "child param"):
self.childParam = childParam
super().__init__(self)
child = Child()
print(child.childParam)
print(child.parentParam)
Output:
child param
<__main__.Child object at 0x0000017CE7C0CAC8>
Why does does child.parentParam
return the child object and not the string "parent param"
? I feel like it should print out the default string set for the Parent class. This appears to be the same syntax as I have been following in this tutorial.
Thanks, everyone.
Upvotes: 3
Views: 689
Reputation: 123521
Your call to super
is wrong. It's not necessary to explicitly pass a self
argument when using it to delegate a method call to a superclass (see the typical usage example shown in the documentation).
In Python 3, calls to super()
with no arguments are equivalent to super(CurrentClass, self).method(arg)
—which was the only way it could be done in Python 2—making it no longer necessary to specify it at all when making calls to superclass methods.
So what's happening, since you passed it in your code, is that it gets interpreted as overriding the default value specified for the parentParam
argument.
Here's doing it properly and the result:
class Parent:
def __init__(self, parentParam="parent param"):
self.parentParam = parentParam
class Child(Parent):
def __init__(self, childParam="child param"):
self.childParam = childParam
super().__init__() # NO NEED TO PASS self.
child = Child()
print(child.childParam) # -> child param
print(child.parentParam) # -> parent param
Upvotes: 4
Reputation: 51683
Because you provide the instance of child (aka self
) to the super call:
class Child(Parent):
def __init__(self, childParam = "child param"):
self.childParam = childParam
super().__init__(self) # here you override the default by supplying this instance
Use:
class Child(Parent):
def __init__(self, childParam = "child param"):
self.childParam = childParam
super().__init__()
instead and you get this output instead:
child param
parent param
Upvotes: 5