对给定的预约记录管理系统程序“预约记录增删改查.py”,使用面向对象方法改写该程序,将所给程序中的函数改写成类中的方法。
时间: 2024-10-25 18:03:26 浏览: 9
将SQLite数据库中的数据共享给其他应用增删改查.rar
原始的`预约记录增删改查.py`程序可能是基于函数的命令行操作,我们可以将其转换成一个面向对象的设计,创建一个名为`AppointmentRecordManager`的类,包含四个相关的类方法来处理预约记录的增加、删除、修改和查询操作。以下是面向对象的改写版本:
```python
class AppointmentRecord:
def __init__(self, id, name, date, time):
self.id = id
self.name = name
self.date = date
self.time = time
class AppointmentRecordManager:
records = []
@classmethod
def add_record(cls, name, date, time):
new_id = len(cls.records) + 1
record = AppointmentRecord(new_id, name, date, time)
cls.records.append(record)
return f"Appointment added successfully. ID: {new_id}"
@classmethod
def delete_record(cls, id):
try:
record_to_delete = [record for record in cls.records if record.id == id]
if record_to_delete:
cls.records.remove(record_to_delete[0])
return f"Appointment with ID {id} deleted."
else:
return "No appointment found with that ID."
except Exception as e:
return str(e)
@classmethod
def update_record(cls, id, name=None, date=None, time=None):
for record in cls.records:
if record.id == id:
if name:
record.name = name
if date:
record.date = date
if time:
record.time = time
return f"Appointment with ID {id} updated."
return "No appointment found with that ID."
@classmethod
def get_records(cls):
return "\nID\tName\tDate\tTime\n" + '\n'.join([str(record) for record in cls.records])
if __name__ == "__main__":
manager = AppointmentRecordManager()
# 示例操作
print(manager.add_record("John Doe", "2023-04-01", "10:00 AM"))
print(manager.get_records())
print(manager.update_record(1, name="Jane Doe", date="2023-04-05"))
print(manager.delete_record(1))
```
在这个版本中,我们定义了一个`AppointmentRecord`类表示预约记录,并在`AppointmentRecordManager`类中添加了相应的方法,如`add_record`、`delete_record`、`update_record`和`get_records`。每个方法都是类方法,可以直接通过类实例调用,无需创建具体的对象。这种方式使得代码更易于维护和扩展。
阅读全文