使函数leisure()成为类car和类boat的函数,在类car和类boat中增加get函数
时间: 2024-06-10 21:10:54 浏览: 7
假设函数leisure()是用来计算某种交通工具的休闲时间的函数,可以将其改写为类car和类boat的成员函数,并在这两个类中添加get函数来获取交通工具的休闲时间。
类Car:
```python
class Car:
def __init__(self, model, speed):
self.model = model
self.speed = speed
def leisure(self):
leisure_time = 100 - self.speed
return leisure_time
def get_leisure_time(self):
return self.leisure()
```
类Boat:
```python
class Boat:
def __init__(self, name, speed):
self.name = name
self.speed = speed
def leisure(self):
leisure_time = 150 - self.speed
return leisure_time
def get_leisure_time(self):
return self.leisure()
```
在这个例子中,类Car和类Boat都有一个leisure()函数,用来计算它们的休闲时间。在类内部,这个函数可以访问类的属性(例如速度),并据此计算出休闲时间。此外,每个类还有一个get_leisure_time()函数,用来获取交通工具的休闲时间。这个函数只是简单地调用leisure()函数并返回结果。
相关推荐
![](https://img-home.csdnimg.cn/images/20210720083646.png)
![](https://img-home.csdnimg.cn/images/20210720083646.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.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)