简体   繁体   English

在没有 arguments 的情况下调用超级初始化方法

[英]calling super init method without arguments

I have a questio about super().__init__() method.我对super().__init__()方法有疑问。 According to W3SCHOOLS the definition and usage (of super) is:根据 W3SCHOOLS 的定义和用法(超级)是:

  • The super() function is used to give access to methods and properties of a parent or sibling class. super() function 用于访问父级或兄弟级 class 的方法和属性。

  • The super() function returns an object that represents the parent class. super() function 返回代表父 class 的 object。

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).但是我真的不明白为什么以及在哪里可以使用super().__init__()方法而在__init__中没有任何参数(因为,即使没有super ,只要我们插入名称,就会调用父 class 的__init__方法括号上的父母的 class )。

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这里我们使用它是因为我们需要在 Rectangle class 上定义self.length, self.width self.width
(we insert length, length). (我们插入长度,长度)。

However i don't know why we use it without any arguments like in the next example.但是我不知道为什么我们在没有任何 arguments 的情况下使用它,就像在下一个示例中一样。
Since i know that we can access the methods and attributes of a parent class without the need to call the super.因为我知道我们可以访问父 class 的方法和属性,而无需调用超级。

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.没有super().__init__() ,它们将无法运行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM