4、 设计一个Medicine(药品)类,包括药名(name)、价格(price)、生产日期(pd)、失效日期(exp)等属性,将价格、生产日期和失效日期设置为私有属性,不允许随意修改,类需要包括计算保质期的方法guarantee_period()和计算药品是否过期的方法is_expire()。用Python代码实现
时间: 2024-01-05 15:05:15 浏览: 40
下面是一个示例的 Medicine 类实现:
```python
import datetime
class Medicine:
def __init__(self, name, price, pd, exp):
self.name = name
self._price = price
self._pd = pd
self._exp = exp
def guarantee_period(self):
exp_date = datetime.datetime.strptime(self._exp, '%Y-%m-%d')
pd_date = datetime.datetime.strptime(self._pd, '%Y-%m-%d')
return (exp_date - pd_date).days
def is_expire(self):
exp_date = datetime.datetime.strptime(self._exp, '%Y-%m-%d')
return exp_date <= datetime.datetime.today()
def get_price(self):
return self._price
def set_price(self, price):
self._price = price
```
这里将价格、生产日期和失效日期设置为私有属性,不允许随意修改。计算保质期的方法 `guarantee_period()` 和计算药品是否过期的方法 `is_expire()` 都使用了 Python 的 datetime 模块进行实现。同时还提供了获取价格和设置价格的方法,因为价格是私有属性不能直接访问。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.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)