python的类的继承和重构
时间: 2024-01-10 19:48:25 浏览: 32
Python中的类继承可以通过在类定义时使用父类名称作为参数来实现。例如:
```python
class Animal:
def __init__(self, name):
self.name = name
def move(self):
print(f"{self.name} is moving")
class Dog(Animal):
def bark(self):
print(f"{self.name} is barking")
dog = Dog("Rufus")
dog.move() # 输出 "Rufus is moving"
dog.bark() # 输出 "Rufus is barking"
```
在上面的例子中,`Dog` 类继承自 `Animal` 类,继承了 `move` 方法,并且还新增加了 `bark` 方法。
类重构指的是对已有类的修改,以改进其功能或性能。例如,我们可以对上例中的 `Animal` 类进行重构:
```python
class Animal:
def __init__(self, name):
self.name = name
def move(self):
print(f"{self.name} is moving")
class Dog(Animal):
def bark(self):
print(f"{self.name} is barking")
def move(self):
print(f"{self.name} is running") # 重构 move 方法
dog = Dog("Rufus")
dog.move() # 输出 "Rufus is running"
dog.bark() # 输出 "Rufus is barking"
```
在上面的例子中,我们重构了 `Animal` 类的 `move` 方法,在 `Dog` 类中重写了 `move` 方法,使其输出更加准确。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)