3 ms·
Nice article, but one thing struck me when reading the code examples posted in the article: What's the use of using kwds in __init__? class Shape(Root):
by lachenmayer 15y ago
Nice article, but one thing struck me when reading the code examples posted in the article: What's the use of using kwds in __init__?
class Shape(Root):
def __init__(self, **kwds):
self.shapename = kwds.pop('shapename')
super().__init__(**kwds)
class ColoredShape(Shape):
def __init__(self, **kwds):
self.color = kwds.pop('color')
super().__init__(**kwds)
I would personally just have written this somewhat similar to this:
class Shape(Root):
def __init__(self, shapename):
self.shapename = shapename
super().__init__()
class ColoredShape(Shape):
def __init__(self, shapename, color):
self.shapename = shapename
self.color = color
super().__init__(shapename)
But then again I'm by no means what anyone could call a Python 'Jedi'. Can anyone explain to me why using kwds in this way would be better? Would it not lead to having to look up the declaration of the class for the exact names of arguments to pop() every time?
- Peristarkawan 15y agoThe reason for using keywords is that there is no guarantee that the next class in the MRO after ColoredShape will be Shape. When the instance is a ColoredShape, it will be, but if ColoredShape is subclassed with a more complex inheritance structure, then something else could end up in between them in the MRO. Thus, ColoredShape.__init__ can't simply pass on shapename to the super method, because that might not be the argument expected by the next __init__ method in the MRO. Instead, each method needs to gracefully accept arbitrary arguments and then pass on whatever it received (minus what it consumed).