为什么我的代码不能正确加载?

时间:2017-02-03 15:05:00

标签: python class dictionary split load

在类中,我们必须使用split()方法为类和字典创建一个保存/加载函数。我设法让保存功能正常工作,但加载功能似乎不适合我。我得到它几乎工作,但保存的文件没有加载,或我得到错误

“playerclass”没有“播放器”属性。需要使用 init 方法。以下是完整的代码def loaddata():主要是关注的领域。

class playerclass:
    name = ""
    phone = ""
    jersey = ""
    def __init__(self, name, phone, jersey):
        self.name = name
        self.phone = phone
        self.jersey = jersey
    def setname(self, name):
        self.name = name
    def setphone(self, phone):
        self.phone = phone
    def setjersey(self, jersey):
        self.jersey = jersey

    def getname(self):
        return self.name
    def getphone(self):
        return self.phone
    def getjersey(self):
        return self.jersey
    def disroster(self):
        print("Player Bio")
        print("-----------")
        print("Name: ", self.name)
        print("Phone #: ", self.phone)
        print("Jersey #: ", self.jersey)

def savedata (players):
    filename = input("Enter file name: ")
    print("Saving....")
    outFile = open(filename, "wt")
    for x in players.keys():
        name = players[x].getname()
        phone = str(players[x].getphone())
        jersey = str(players[x].getjersey())
        outFile.write(name+","+phone+","+jersey+"\n")
    print("Save Complete")
    outFile.close()

 def loaddata ():
    players = {}
    filename =input("Enter filename to load: ")
    inFile = open(filename, "rt")
    print("Loading.....")
    while True:
        inLine = inFile.readline()
        if not inLine:
            break
        inLine = inLine [:-1]
        name, phone, jersey = inLine.split(",")
        players[name] = playerclass(name, phone, jersey)
    print("Load Successfull.")
    inFile.close()
    return players


def roster(players):
    if len(players) == 0:
        print("No players on roster: ")
    else:
        for x in players.keys():
            players[x].disroster()

def add_player (players):
    newName=input("Enter name of player to add: ")
    newPhone = int(input("Enter phone number of player: "))
    newJersey = int(input("Enter number of assigned jersey: "))
    players[newName]= playerclass(newName, newPhone, newJersey)
    return players

def ed_player (players):
    oldName = input("Enter players name to edit: ")
    if oldName in players:
        newName = input("Enter new name for player: ")
        newPhone = int(input("Enter new phone number for player: "))
        newJersey = int(input("Enter newly assigned jersey number: "))
        players[oldName] = playerclass(newName, newPhone, newJersey)
    return players

def del_player(players):
    delName = input("Enter players name to delete from roster: ")
    if delName in players:
        del players[delName]
    return players

def displayMenu():
    print("-------Main Menu-------")
    print("1. Display Team Roster.")
    print("2. Add Member.")
    print("3. Remove Member.")
    print("4. Edit Member.")
    print("5. Save Data.")
    print("6. Load Data.")
    print("9. Exit Program.")
    return  input("Menu Choice:  ")

print("Team Management Tools.")

players = {}
menu_choice = displayMenu()
while menu_choice != '9':
    if menu_choice == '1':
        roster(players)
    elif menu_choice == '2':
        players = add_player (players)
    elif menu_choice == '3':
        players = del_player (players)
    elif menu_choice == '4':
        players =  ed_player (players)
    elif menu_choice == '5':
        savedata (players)
    elif menu_choice == '6':
        loaddata ()
    menu_choice = displayMenu()
print("Updating roster Goodbye:")

1 个答案:

答案 0 :(得分:0)

players = {}功能移除loaddata,它将正确加载。

如果您实际上希望在加载时重置字典的内容(这可能是您的意图,虽然我会说这是一个值得怀疑的设计决定),您可以这样做:

def loaddata():
    global players
    players = {}
    ...

这是因为你写的任何变量都被认为是局部变量(如函数的本地变量),除非你另有说法。

我可能会忽略某些东西,但是我没有看到任何试图从任何对象读取player属性的内容,因此我不确定错误来自何处。它来自此代码的不同版本吗?或者,如果是具有该错误的发布版本,您是否可以准确提供导致错误的系列输入?

此答案的其余部分与您的问题没有直接关系,只是基于我在代码中注意到的事项的一些提示。

我会删除:

name = ""
phone = ""
jersey = ""

因为你在__init__中设置它们所以它们是多余的而且没有做任何事情。对于循环遍历文件中的行,可以使用for循环,它比while循环更易读。例如:

for line in infile:
  print(line)

你应该调查with。它是另一种类型的块,它们在处理文件时非常有用,因为它们会在块结束时自动关闭文件,因此您不必这样做。举个例子:

with open("foo", "r") as stream:
    for line in stream:
        print(line)
# stream got implicitly closed because the block ended