class Person:
__name = ""
__contacts = []
__age = 0
__vaccination_state = False
__health_state = True
__quarantine_state = True
__symptom = "symptomatic"
def __init__(self, name, contacts, age, vaccination_state, health_state, quarantine_state, symptom):
self.__name = name
self.__age = age
self.__contacts = contacts
self.__vaccination_state = vaccination_state
self.__health_state = health_state
self.__quarantine_state = quarantine_state
self.__symptom = symptom
def GetName(self):
return self.__name
def GetAge(self):
return self.__age
def GetContacts(self):
return self.__contacts
def GetVaccination(self):
return self.__vaccination_state
def GetHealth(self):
return self.__health_state
def GetQuarantine(self):
return self.__quarantine_state
def GetSymptom(self):
return self.__symptom
def SetName(self, name):
self.__name = name
def SetAge(self, age):
self.__age = age
def SetAllContacts(self, contacts):
self.__contacts = contacts
def AddSingleContact(self, contact):
self.__contacts.append(contact)
def SetVaccination(self, vaccination_state):
self.__vaccination_state = vaccination_state
def SetHealth(self, healthState):
self.__health_state = healthState
self.CheckPositive()
def SetQuarantine(self, quarantine_state):
self.__quarantine_state = quarantine_state
def SetSymptom(self, symptom):
self.__symptom = symptom
def CheckPositive(self):
if self.__health_state == False:
self.__quarantine_state = True
start = datetime.datetime.now()
end = start + datetime.timedelta(10)
for i in range(len(self.__contacts)):
getattr(Person, self.GetContacts()[i]).SetQuarantine(True)
print(self.GetContacts()[i], " and his/her close contacts have been notified.\n", "Quarantine starts at", start, "and ends at", end)
for i in range(len(self.__contacts)):
getattr(Person, self.GetContacts()[i]).SetQuarantine(True)
A = Person("A", ["Z"], 17, True, True, False, "NA")
Z = Person("Z", ["A"], 17, True, True, False, "NA")
A.SetHealth(False) SetQuarantine(True)是我要调用的类中的一个函数。self.GetContacts(i)的返回值是一个列表。因此,self.GetContacts()i是一个字符串,例如,"name“。但是,我希望获得一个属性,以便可以调用函数SetQuarantine(True)。该属性与字符串具有相同的值,但我不知道如何转换它。谢谢!
发布于 2022-01-01 23:02:15
您的问题源于试图执行以下操作:getattr(Person, self.GetContacts()[i]).SetQuarantine(True)。您正在尝试访问一个不存在的Person.Z属性。因此Python会抛出一个错误。
要解决这个问题,您需要做两件事:
下面是一个修改后的CheckPositive函数以及一些修改过的驱动程序代码:
def CheckPositive(self):
if self.__health_state == False:
self.__quarantine_state = True
start = datetime.datetime.now()
end = start + datetime.timedelta(10)
for i in range(len(self.__contacts)):
print(self.__contacts[i].GetName(), "has been notified.\n", "Quarantine starts at", start, "and ends at", end)
self.__contacts[i].SetQuarantine(True)
A = Person("A", [], 17, True, True, False, "NA")
Z = Person("Z", [], 17, True, True, False, "NA")
A.AddSingleContact(Z)
Z.AddSingleContact(A)
A.SetHealth(False)https://stackoverflow.com/questions/70537570
复制相似问题