使用用户输入实例化类

2024-05-18 23:39:51 发布

您现在位置:Python中文网/ 问答频道 /正文

我刚刚开始学习关于课堂的知识。在我正在学习的示例中,我注意到所有实例化的内容都是如何硬编码到示例中的。我想尝试并弄清楚是否可以通过用户输入来实例化,而不必这样做。 在第74/75行中,我的期望是print(RecordID_map_PilotID[valUE].flownhours)打印我为特定实例选择记录的小时数。相反,我遇到了以下令人讨厌的错误:

Traceback (most recent call last):
  File "oop_test.py", line 74, in <module>
    RecordID_map_PilotID[valUE].recordflytime(loghours)
AttributeError: 'str' object has no attribute 'recordflytime'

有人能帮我理解为什么我想要Python做的事情实际上不起作用吗? 谢谢大家!

PilotID_ClassValCalls = {}
RecordID_map_PilotID = {}
class PilotRecord:
    department = "Aviation"
    asset = "Employee"
    assetcategory = "FTE"
    flownhours = 0

    def __init__(self, pilotid, name, age, licensestatus, licenseexpiration, shiptype, callsign, flownhours):

        self.pilotid = pilotid
        self.name = name
        self.age = age
        self.licensestatus = licensestatus
        self.licenseexpiration = licenseexpiration
        self.shiptype = shiptype
        self.callsign = callsign
        self.flownhours = flownhours

    def __str__(self):

        return f"{self.pilotid} has an {self.licensestatus} license with an expiration date of {self.licenseexpiration} with the following callsigns:\n {self.callsign} ."

    def recordflytime(self, hours):
        self.flownhours = self.flownhours + hours

def Adding_Pilot_Records(): #This definitions created new pilot records and instantiates a new object for each pilot rcord that is created. In addition memory values are stored in Dict

    add_records_number = int(input("How many pilot records would you like to add? "))

    for eachrecord in range(add_records_number):


        record_store = [input("Please provide pilot ID: "), input("Please provide pilot Name: "), int(input("Please provide pilot Age: ")),
        input("Please provide pilot licensestatus: "), input("Please provide pilot licenseexpiration: "), input("Please provide pilot shiptype: "), input("Please provide pilot callsign: "), 0]

        PilotID_ClassValCalls.update({eachrecord + 1 : record_store[0]})
        RecordID_map_PilotID.update({PilotID_ClassValCalls[eachrecord+1]: record_store[0]}) 

        PilotID_ClassValCalls[eachrecord+1] =  PilotRecord(record_store[0], record_store[1], record_store[2], record_store[3], record_store[4], record_store[5], record_store[6], record_store[7])

while True == True:
    print("Hello, Welcome to the PILOT RECORD DATABASE\n",
    "What would you like to do with the Records?:\n\n",
    " \t1 - \"Add\"\n",
    " \t2 - \"Log\"\n",
    " \t3 - \"Delete\"\n",
    " \t4 - \"Quit\"\n")

    userchoice = str(input().lower().strip())

    try:

        if userchoice == "1" or userchoice == "add":
            Adding_Pilot_Records()
            continue

        elif userchoice == "2" or userchoice == "log":

            while userchoice == "2" or userchoice == "log":

                pickarecord = str(input("Which Record ID would you like to create a log for? ")).split()
                pickarecord_yesno = input(f"Selected Record >>> {RecordID_map_PilotID[pickarecord[0]]}, Is this the correct record? [Y] [N] [Quit]").upper().split()
                userchoice = ""
                if pickarecord_yesno[0] == "Q" or pickarecord_yesno[0] == "QUIT":
                    break
                elif pickarecord_yesno[0] == "Y" or pickarecord_yesno[0] == "YES":
                    userchoice = ""
                    loghours = int(input(f"How many hours would you like to log?"))
                    pickarecord = str(pickarecord[0])
                    for record, valUE in RecordID_map_PilotID.items():
                        if pickarecord in valUE:
                            RecordID_map_PilotID[valUE].recordflytime(loghours)
                            print(RecordID_map_PilotID[valUE].flownhours)

                elif pickarecord_yesno[0] == "N" or pickarecord_yesno == "NO":
                    userchoice = "2"
                    continue





        elif userchoice == "3" or userchoice == "delete":
            continue

        elif userchoice == "4" or userchoice == "quit":
            break

    except ValueError:
            print("Sorry an Error has occurred")

Tags: orstoreselfmapinputrecordpleaseprovide
1条回答
网友
1楼 · 发布于 2024-05-18 23:39:51

这是导致错误的行:

RecordID_map_PilotID[valUE].recordflytime(loghours)

您正试图在RecordID_map_PilotID[valUE]上调用.recordflytime()。但是RecordID_map_PilotID是类型为str -> str的字典,因此RecordID_map_PilotID[valUE]引用字符串,而字符串没有.recordflytime()方法

我可以看出它是一个字符串,因为这一行是唯一修改它的行:

RecordID_map_PilotID.update({PilotID_ClassValCalls[eachrecord+1]: record_store[0]})

因此,您使用单个键/值对,用另一个来更新一个dict,键为PilotID_ClassValCalls[eachrecord+1],值为record_store[0]PilotID_ClassValCalls的填充方式类似,其值通常也是record_store[0]。然后用调用input()的结果填充记录存储,这是一个字符串

我建议您阅读一些关于Python中面向对象编程的示例——我认为您正在尝试“手工”完成Python中存在的特定数据结构和方法更好的工作

更一般地说,最好将保存和操作数据的结构与获取进程输入的代码分开。毕竟,您现在希望通过用户直接输入来操作这些对象,但是如果您将内容保存到文件中,稍后再将其读回会怎么样?或者从网页上调用代码?您可能希望使用相同的类,但不需要直接调用input(),从而导致代码需要控制台上的输入

相关问题 更多 >

    热门问题