python中调用父类的方法
时间: 2023-09-03 07:12:57 浏览: 45
在Python中,子类可以通过super()函数来调用父类的方法。super()函数返回一个super对象,这个对象可以调用父类的方法。
super()函数的语法如下:
```python
super([type[, object-or-type]])
```
其中,type是一个类,object-or-type是一个类的实例或者这个类本身。如果省略了这两个参数中的一个或两个,super()函数会根据上下文自动推断。
使用super()函数调用父类的方法,可以在子类中重写父类的方法,并且在子类中调用父类的方法。例如:
```python
class ParentClass:
def say_hello(self):
print("Hello, I'm the parent.")
class ChildClass(ParentClass):
def say_hello(self):
super().say_hello()
print("Hello, I'm the child.")
obj = ChildClass()
obj.say_hello()
```
在这个例子中,我们定义了一个ParentClass父类和一个ChildClass子类,子类重写了父类的say_hello()方法,并且使用super().say_hello()来调用父类的say_hello()方法。当我们创建ChildClass对象obj并调用它的say_hello()方法时,输出将是:“Hello, I'm the parent.”和“Hello, I'm the child.”。
注意,使用super()函数调用父类的方法时,需要注意以下几点:
- super()函数只能调用父类的方法,不能调用父类的属性;
- super()函数调用的是父类的方法,而不是当前类的方法;
- 如果有多个父类,super()函数默认调用第一个父类的方法,也可以通过传递参数来指定调用的父类。