For class inheritance, what is the role of the statement calling the super _init__?

Asked 2 years ago, Updated 2 years ago, 19 views

I am not sure about the super(PlotCanvas,self).__init__(self.fig) part of this class.
Please tell me the role of this sentence.

 classPlotCanvas (FigureCanvas):

    def__init__(self, parent=None, width=5, height=4, dpi=100):
        self.fig=Figure(figsize=(width, height), dpi=dpi)
        self.axes=self.fig.add_subplot(111)

        super(PlotCanvas, self).__init__(self.fig)
        self.setParent(parent)

        FigureCanvas.setSizePolicy(
                self,
                QSizePolicy.Expanding,
                QSizePolicy.Expanding
                )
        FigureCanvas.updateGeometry(self)
        self.plot()

python

2022-09-30 16:35

1 Answers

In child classes, you can override the functions of the parent class.And if overridden, the functions defined in the parent class are not called.
This is also true for functions such as __init__

.

I made a little example.

class rectangle (object):
    def_init__(self,h,w):
        self.vertical = h
        self. Horizontal = w

    def Area (self):
        return self.vertical*self.horizontal

    Def lap (self):
        return (self.vertical + self.horizontal)*2

    Area of the def inscribed circle (self):
        return None


class square (rectangular):
    def__init__(self,e):
        self. One side = e
        super(square, self).__init__(self.side, self.side)
        self. radius of the inscribed circle = e/2

    Area of the def inscribed circle (self):
        return self. radius of inscribed circle *self. radius of inscribed circle * 3.14


a = square (10)

print(a. area())
print(a. circumference())
print(a. the area of the inscribed circle())

In a square class, you can call the area function defined by the parent class rectangle, but the vertical and horizontal variables used in the area function are set by the rectangular class __init__.
The square class initializes one side of its own variable by defining _init__, but it does not initialize both vertical and horizontal.

Thus, the _init__ function, called when an instance is generated, initializes the variables and other factors necessary to operate that instance, so it is common to call the parent class _init__ in the child class _init__.


2022-09-30 16:35

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.