I have a questio about super().__init__()
method. According to W3SCHOOLS the definition and usage (of super) is:
The super()
function is used to give access to methods and properties of a parent or sibling class.
The super()
function returns an object that represents the parent class.
However i really can't understand why and where can we use super().__init__()
method without any argument in __init__
(since, even without super
, the __init__
method of the parent class is called as soon as we insert the name of the parent's class on the parenthesis).
I AM NEW TO Objected Oriented programming so i am just trying to understand how it works!!!
To help you understand my problem see the example below:
class Rectangle:
def __init__(self, length, width):
self.length = length
self.width = width
def area1(self):
return self.length * self.width
class Square(Rectangle):
def __init__(self, length):
super().__init__(length, length)
square = Square(4)
square.area()
Here we use it because we need to define the self.length, self.width
on the Rectangle class
(we insert length, length).
However i don't know why we use it without any arguments like in the next example.
Since i know that we can access the methods and attributes of a parent class without the need to call the super.
class Example(QMainWindow):
def __init__(self):
super().__init__()
self.lineEntry = QLineEdit(self)
self.lineEntry.move(16,16)
self.lineEntry.resize(200,40)
self.setGeometry(50,50,320,200)
self.setWindowTitle("QLineEdit Example")
self.show()
app = QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())
Not every attribute is passed to the constructor - some may be private attributes that have default values assigned in the constructor. Additionally, the parent class's constructor may do things other than just assigning attributes, such as setting up a cache. Without the super().__init__()
, they won't run.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.