首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

使用super与类方法

在Python中,super() 函数用于调用父类(超类)的方法。在这个例子中,我们将使用 super() 函数来调用父类的 __init__() 方法,并在子类的 __init__() 方法中添加一些额外的功能。

首先,我们需要定义一个父类和一个子类。父类将包含一个名为 parent_method() 的方法,而子类将包含一个名为 child_method() 的方法。

代码语言:python
复制
class Parent:
    def __init__(self):
        print("Parent's __init__() method called")

    def parent_method(self):
        print("Parent's method called")


class Child(Parent):
    def __init__(self):
        super().__init__()
        print("Child's __init__() method called")

    def child_method(self):
        print("Child's method called")

在这个例子中,我们使用 super() 函数在子类的 __init__() 方法中调用父类的 __init__() 方法。当我们创建一个 Child 类的实例时,将会看到以下输出:

代码语言:txt
复制
Parent's __init__() method called
Child's __init__() method called

这表明,Child 类的 __init__() 方法成功地调用了父类 Parent__init__() 方法。

现在,我们可以创建一个 Child 类的实例,并调用 parent_method()child_method() 方法:

代码语言:python
复制
child = Child()
child.parent_method()
child.child_method()

输出将如下所示:

代码语言:txt
复制
Parent's method called
Child's method called

这表明,我们成功地在子类中覆盖了父类的方法,并且可以在子类中调用父类的方法。

总之,super() 函数可以用于在子类中调用父类的方法,从而实现代码重用和继承。

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

领券