Python方法重写
时间: 2023-12-25 15:28:55 浏览: 38
以下是Python方法重写的几种方法:
1. 在子类中重新定义和父类同名的方法
```python
class ParentClass:
def override_method(self):
print("This is the parent class method")
class ChildClass(ParentClass):
def override_method(self):
print("This is the child class method")
child = ChildClass()
child.override_method() # 输出:This is the child class method
```
2. 在子类代码中,使用super().方法名()调用父类中的功能
```python
class ParentClass:
def override_method(self):
print("This is the parent class method")
class ChildClass(ParentClass):
def override_method(self):
super().override_method()
print("This is the additional functionality in the child class method")
child = ChildClass()
child.override_method() # 输出:This is the parent class method This is the additional functionality in the child class method
```
3. 书写新的功能
```python
class ParentClass:
def override_method(self):
print("This is the parent class method")
class ChildClass(ParentClass):
def new_method(self):
print("This is a new method in the child class")
child = ChildClass()
child.override_method() # 输出:This is the parent class method
child.new_method() # 输出:This is a new method in the child class
```