首页 > 解决方案 > 如何结合两个类?

问题描述

我正在尝试使用 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):

我被困在这一点上。我不知道如何使用类来完成这项工作。

标签: python

解决方案


您的代码中有一些错误,我已修复。我想提出这种关系,其中 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已接种疫苗,则vaccineparam 将是一个Vaccination对象,否则,它将是None.

最后,我建议您阅读OOP中类之间的关系。上面的例子是一个组合,它是这种范式中使用的一种关系。


推荐阅读