python - 如何结合两个类?
问题描述
我正在尝试使用 python 中的类函数编写疫苗接种证书的代码。我知道我需要一门针对患者的课程和一门针对疫苗的课程,但我不知道如何将两者联系起来,或者我是否需要额外的课程。我需要能够输入用户以检查他们是否有证书。没有 GUI,只是基于终端的模拟代码。
class Vaccination():
def _init_(self, ID, name, Vdate, address):
self.ID = ID
self.name = name
self.Vdate =Vdate
self.address = address
def AstraZeneca(self):
return ID
AstraZeneca = Vaccination("123","AstraZeneca","23/06/2021","Male","Robert-Koch")
class Patient(object):
def _init_(self, ID, name, bdate, gender, phone, address):
self.ID = ID
self.name = name
self.address = address
self.bdate = bdate
self.gender = gender
self.address = address
def get_name(self):
我被困在这一点上。我不知道如何使用类来完成这项工作。
解决方案
您的代码中有一些错误,我已修复。我想提出这种关系,其中 aPatient
有一个 Vaccination
。默认情况下,患者没有接种过疫苗,可以在Patient
构造函数中看到(默认vaccine
为is None
):
class Vaccination(object):
def __init__(self, ID, name, Vdate, address):
self.ID = ID
self.name = name
self.Vdate =Vdate
self.address = address
def AstraZeneca(self):
return self.ID
class Patient(object):
def __init__(self, ID, name, bdate, gender, phone, address, vaccine=None):
self.ID = ID
self.name = name
self.address = address
self.bdate = bdate
self.gender = gender
self.address = address
self.vaccine = vaccine
def get_name(self):
print(self.name)
# An astrazeneca
astrazeneca = Vaccination('1', 'Astrazeneca', '23/06/2023', 'An address')
# Jhon Doe has been vaccined with astrazeneca
patient_1 = Patient('123','Jhon Doe','23/06/1998','Male', '3345556', 'An address', astrazeneca)
# Some else hasn't been vaccined yet.
patient_2 = Patient('123','Some Else','23/06/1978','Male', '56456', 'An address2')
# Here you can access the Jhon Doe's vaccine id
# Although, If I were you I'd change the name method for something like get_id()
print(patient_1.vaccine.AstraZeneca())
如果 aPatient
已接种疫苗,则vaccine
param 将是一个Vaccination
对象,否则,它将是None
.
最后,我建议您阅读OOP中类之间的关系。上面的例子是一个组合,它是这种范式中使用的一种关系。
推荐阅读
- java - Javalin,无法获取请求正文,除非直接从 HttpServlet
- html - 一些字体很棒的图标没有显示
- python - 在 python 中为电报机器人创建良好的数据库
- java - 如何使用 Oracle 12c 数据库配置 Jasper 服务器
- android - 弹出软键盘时保持视图组可见
- node.js - 如何修复“错误:找不到 Python 可执行文件“python”,您可以设置 PYTHON 环境变量。” ubuntu nodejs npm
- python - 如何检测用于在特定字段的表单中输入字母的所有框?
- excel - 计算最后使用的行时出现错误 1004
- camera - 如何防止 SceneKit 在设备旋转时更改相机 FOV / 位置?
- excel - 如何获取地址单元格