深度阅读

How do I use the super() function to initialize a parent class in Python?

作者
作者
2023年08月22日
更新时间
8.18 分钟
阅读时间
0
阅读量

You can use the super() function to initialize a parent class in Python. The super() function returns an object that allows you to call methods of a parent class.

Here’s an example of how to use super() to call the __init__ method of a parent class in a subclass:

class ParentClass:
    def __init__(self, x, y):
        self.x = x
        self.y = y

class ChildClass(ParentClass):
    def __init__(self, x, y, z):
        super().__init__(x, y)
        self.z = z

In the example above, ChildClass is a subclass of ParentClass. When ChildClass is instantiated, the __init__ method of ParentClass is called using super().__init__(x, y) within the __init__ method of ChildClass. This initializes the x and y attributes of ParentClass, and the z attribute of ChildClass.

博客作者

热爱技术,乐于分享,持续学习。专注于Web开发、系统架构设计和人工智能领域。