如何在Python中使用super()函数进行父类调用?

我想知道如何在Python中使用super()函数来调用父类方法。我已经创建了一个子类,并且它继承了父类的某些属性和方法,但我想调用父类的方法来完成我的子类需求。我尝试了一些方法,但没有得到预期的结果。有没有老师能够教我具体如何使用super()函数来实现父类的调用呢?谢谢!

提问时间:2023-05-14 18:00:23 编辑时间:2023-05-14 18:00:25 提问者: Velvet_Lover
  • Crimson_Sky
    10

    当你创建一个子类并继承了父类的一些属性和方法时,你可以使用super()函数来调用父类的方法。使用super()函数,你可以在子类中直接调用父类的方法,而无需指定父类。以下是一个示例:

    class ParentClass:
        def __init__(self):
            self.parent_var = "I am a parent class variable!"
    
        def parent_method(self):
            print("I am a method defined in the parent class.")
    
    
    class ChildClass(ParentClass):
        def __init__(self):
            super().__init__()  # Initialize parent class
            self.child_var = "I am a child class variable!"
    
        def child_method(self):
            super().parent_method()  # Call parent class method
            print("I am a method defined in the child class.")
    
    
    child_obj = ChildClass()
    child_obj.child_method()
    

    在以上代码中,我们首先定义了一个父类ParentClass,并在其中定义了一个属性和一个方法。接着我们创建了一个子类ChildClass,并通过继承ParentClass来继承了其属性和方法。在子类ChildClass中,我们使用super()函数来初始化父类中定义的属性,并使用super()函数来调用父类中定义的方法。最后,我们创建了一个ChildClass的实例child_obj,并调用了其方法child_method()。

    运行以上代码,输出结果为:

    I am a method defined in the parent class.
    I am a method defined in the child class.
    

    注意,当使用super()函数时,需要确保父类中被继承的方法已经定义好,否则可能会出现错误。另外需要注意的是,在Python 2.x版本中,需要使用类似以下的方式使用super()函数:super(ChildClass, self)._init_()

    回答时间:2023-05-15 02:43:08