当你创建一个子类并继承了父类的一些属性和方法时,你可以使用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_()
。