设计一个Medicine(药品)类,包括药名(name)、价格(price)、生产日期(pd)、失效日期(exp)等属性,将价格、生产日期和失效日期设置为私有属性,不允许随意修改,类需要包括计算保质期的方法guarantee_period()和计算药品是否过期的方法is_expire()。用Python代码实现from datetime import datetime class Medicine(): def __init__(self,name,price,pd,exp): self.name=name self.__price=price self.__pd=pd self.__exp=exp def show(self): print("药品名称:",self.name) print("价格:",self.__price) def guarantee_period(self): date1=datetime.strptime(self.__pd,"%Y-%m-%d") date2=datetime.strptime(self.__exp,"%Y-%m-%d") minus=date2-date1 return f"保质期为{minus.days}天" def is_expire(self): today=datetime.now() pdd=datetime.strptime(self.__exp,"%Y-%m-%d") if today>pdd: return "药品已过期" else: return "药品未过期" if __name__=="__main__": s1=Medicine("冬凌草片",20,"2022-06-17","2024-06-17") s1.show() s1.guarantee_period() s1.is_expire()查看此答案的错误,给出修改方案
时间: 2023-12-22 20:03:42 浏览: 46
这个实现看起来已经很好了,但是在调用 `guarantee_period()` 和 `is_expire()` 方法时,没有打印出返回值。可以在调用方法时添加 `print()` 函数来打印返回值。
此外,如果想要用户能够修改药品价格、生产日期和失效日期,可以在类中添加相应的 setter 方法。修改后的代码如下:
```python
from datetime import datetime
class Medicine():
def __init__(self, name, price, pd, exp):
self.name = name
self.__price = price
self.__pd = pd
self.__exp = exp
def show(self):
print("药品名称:", self.name)
print("价格:", self.__price)
def guarantee_period(self):
date1 = datetime.strptime(self.__pd, "%Y-%m-%d")
date2 = datetime.strptime(self.__exp, "%Y-%m-%d")
minus = date2 - date1
return f"保质期为{minus.days}天"
def is_expire(self):
today = datetime.now()
pdd = datetime.strptime(self.__exp, "%Y-%m-%d")
if today > pdd:
return "药品已过期"
else:
return "药品未过期"
def set_price(self, price):
self.__price = price
def set_pd(self, pd):
self.__pd = pd
def set_exp(self, exp):
self.__exp = exp
if __name__ == "__main__":
s1 = Medicine("冬凌草片", 20, "2022-06-17", "2024-06-17")
s1.show()
print(s1.guarantee_period())
print(s1.is_expire())
s1.set_price(30)
s1.set_pd("2022-07-17")
s1.set_exp("2024-07-17")
s1.show()
print(s1.guarantee_period())
print(s1.is_expire())
```
这样,用户就可以通过类中的 setter 方法来修改药品的价格、生产日期和失效日期了。