在 python3 中获取 AttributeError

Getting an AttributeError in python3

所以,我是编程方面的新手,我一直在从事一些小项目以尝试巩固我所学的知识。我有这个患者数据库 UI 我一直在制作,它使用的是字典。我现在学会了使用 类 来代替,这样我就可以在一个键中包含更多的数据,而不仅仅是一个变量,但是当我试图引用一个属性来输出时,它给我属性错误..它几乎和我之前使用的代码一样但是包含 .age.. 任何人都可以帮助我并解释为什么我不能使用我以前用于字典的“请求”行并且可能会提出解决方法? error code image

class Patient:
    def __init__(patient, color, age):
        patient.color = color
        patient.age = age

felix = Patient ("White_British", 21)
print(felix.color)

while True:
    print ("What would you like to do?")
    
    usin = str(input("  "))
    
# Find Patient Age Function
    
    if usin == "find patient age":
        try: 
            request = str(input("Name of patient: "))
            print (request + "'s age is " + request.age + " Years"

任何帮助将不胜感激,我知道这似乎是一个愚蠢的问题。

request 不是 Patient class 的实例。您已使用 input() 检索用户输入,使用 str() 将其转换为字符串,并将 request 设置为等于结果。所以 request 没有 age 属性,因为它是一个字符串而不是 Patient.

我重新格式化了一下,但这是我得到的!这 运行 对我来说很好。如果您喜欢它并且对您有用,请随时采纳并编辑它。

class Patient:
    def __init__(self, name, color, age):
        self.name = name
        self.color = color
        self.age = age


felix = Patient('Felix', 'White British', 21)

verified_action = False

while not verified_action:
    user_in = input('What would you like to do?\n').lower()
    if user_in == "find patient age":
        verified_action = True
    else:
        print(f'{user_in} is not a valid input, please try again.')

picked_patient = False

while not picked_patient:
    request = input("Name of patient: ").lower()
    if request == 'felix':
        name = felix.name
        age = felix.age
        color = felix.color
        picked_patient = True
    else:
        print(f'{request} not recognized, please try again.')

print(f"{name}'s age is {age} years.")

您可以在继续添加患者时继续添加 elif 语句,只需将它们各自的变量设置为:

name = timothy.name
# etc.

但是,随着时间的推移,这会变得很麻烦,因此也许将这些数据存储在 Pandas DataFrame 之类的东西中,然后访问该 DataFrame 以获取信息会快得多。医院或任何使用此应用程序的人会发现,不仅可以更轻松地检索大量信息,还可以非常轻松地添加这些信息,而无需编写额外的代码。

希望对您有所帮助!