I'm reading Raymond Hettinger's Python’s super() considered super! About a page in, there's this example:
class Shape:
def __init__(self, shapename, **kwds):
self.shapename = shapename
super().__init__(**kwds)
class ColoredShape(Shape):
def __init__(self, color, **kwds):
self.color = color
super().__init__(**kwds)
cs = ColoredShape(color='red', shapename='circle')
Why is it necessary to call super()
in Shape
here? My understanding is that this calls object.__init__(**kwds)
since Shape
implicitly inherits from object
.
Even without that statement, we've already
- established
shapename
already in the parent's__init__
, - established the child class's
color
in an explicit method override, - then invoked the parent's
__init__
withsuper()
inColoredShape
.
As far as I can tell, dropping this line produces the same behavior & functionality:
class Shape: # (object)
def __init__(self, shapename, **kwds):
self.shapename = shapename
# super().__init__(**kwds)
class ColoredShape(Shape):
def __init__(self, color, **kwds):
self.color = color
super().__init__(**kwds)
def check(self):
print(self.color)
print(self.shapename)
cs = ColoredShape(color='red', shapename='circle')
cs.check()
# red
# circle
What is the purpose of super()
within Shape
here?
**kwds
and removeshapename
from**kwds
- andShape
parent is not important in this example. MaybeShape
should have parent but it is not main element in all example.