I have found a code in realpython.com about python super() and I don't understand what is the purpose of the super() in Rectangle and Triangle init method if both classes have no parent (don't inherit).
class Rectangle:
def __init__(self, length, width, **kwargs):
self.length = length
self.width = width
super().__init__(**kwargs)
def area(self):
return self.length * self.width
class Square(Rectangle):
def __init__(self, length, **kwargs):
super().__init__(length=length, width=length, **kwargs)
class Triangle:
def __init__(self, base, height, **kwargs):
self.base = base
self.height = height
super().__init__(**kwargs)
def tri_area(self):
return 0.5 * self.base * self.height
class RightPyramid(Square, Triangle):
...
CodePudding user response:
This way, these classes can work with multiple-inheritance, and they may get ancestors unknown at coding time - the call to super
, passing any unknown parameters they may have got, ensures they will play nice when used this way.
For example, let's suppose these shapes are used to represent the creation concrete 3D printing plastic objects.
class Print3D:
def __init__(self, *, filament="PLA", **kw):
self.filament=filament
print("Print3D part initialized")
super().__init__(**kwargs)
One now can do:
class PrintedSquare(Square, Print3D):
pass
mysquare = PrintedSquare(length=20, filament="PVC")
and everything will just work.