0

我刚刚开始学习课程。在我正在学习的示例中,我注意到所有被实例化的东西是如何被硬编码到示例中的。我想通过用户输入尝试弄清楚是否可以在不必这样做的情况下进行实例化。在第 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")
4

1 回答 1

0

这是导致错误的行:

RecordID_map_PilotID[valUE].recordflytime(loghours)

您正在尝试调用.recordflytime(). RecordID_map_PilotID[valUE]ButRecordID_map_PilotID是 type 的字典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()导致您的代码期望在控制台上输入。

于 2020-05-03T01:50:02.533 回答