提示信息

Python super()

肆无忌惮 已关注

The super() function in Python is used to refer to the parent class. It returns a temporary object of the superclass, which allows you to call its methods.

The super() function is often used in inheritance in order to call a method from the parent class, while also having the ability to add additional functionality to it in the child class.

Here's a basic example of how super() can be used:

  1. class ParentClass:
  2. def __init__(self):
  3. self.name = "Parent"
  4. def display(self):
  5. print("This is the Parent class")
  6. class ChildClass(ParentClass):
  7. def __init__(self):
  8. super().__init__() # calling the parent class' __init__() method
  9. self.name = "Child"
  10. def display(self):
  11. super().display() # calling the parent class' display() method
  12. print("This is the Child class")
  13. child = ChildClass()
  14. child.display()

In this example, we create a parent class ParentClass with a display() method. We then create a child class ChildClass that inherits from ParentClass. In the child class, we use super().__init__() to call the parent class' __init__() method, which sets the name attribute to "Parent". We also use super().display() to call the parent class' display() method and then print "This is the Child class".

When we create an instance of ChildClass and call the display() method, it first calls the parent class' display() method, printing "This is the Parent class", and then continues to execute the lines of code in the child class' display() method, printing "This is the Child class".

    遇到难题? "AI大模型GPT4.0、GPT" 是你的私人解答专家! 点击按钮去提问......
肆无忌惮 关注 已关注

最近一次登录:2023-10-09 16:02:50   

暂时还没有签名,请关注我或评论我的文章
×
免费图表工具,画流程图、架构图