举例说明使用聚合方式将多继承改为单继承
时间: 2023-10-03 20:06:51 浏览: 48
假设有以下的多继承关系:
```
class A:
def method_a(self):
print("This is method A.")
class B:
def method_b(self):
print("This is method B.")
class C(A, B):
def method_c(self):
print("This is method C.")
```
现在我们想要将 C 类的继承关系改为单继承,使用聚合方式。我们可以将 A 和 B 的功能分别提取出来,然后在 C 类中调用这些功能:
```
class A:
def method_a(self):
print("This is method A.")
class B:
def method_b(self):
print("This is method B.")
class C:
def __init__(self):
self.a = A()
self.b = B()
def method_c(self):
print("This is method C.")
self.a.method_a()
self.b.method_b()
```
在上面的代码中,我们在 C 类的 `__init__` 方法中创建了 A 和 B 的实例,并将它们存储在 C 类的实例变量中。在 C 类的 `method_c` 方法中,我们调用了 A 和 B 的方法,并且在方法中也可以访问 C 类的实例变量。这种方式就实现了单继承的效果。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![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)