Chase Quinn
Chase Quinn

Reputation: 60

Python Dictionary As Object Error

I have an error that I can not get my head around. The code is as follows:

def saveData():
    filename = input("Filename to save: ")
    print("Saving Data...")
    outFile = open(filename, "wt")
    for x in team.keys():
        name = team[x].getname()
        phone = team[x].getphone()
        jersey = team[x].getjersey()
        outFile.write
        (name+", "+phone+", "+jersey+"\n")
    print("Data saved.")
    outFile.close()

def loadData():
    self = {}
    filename = input("Filename to load: ")
    inFile = open(filename, "rt")
    print("Loading data...")
    while True:
        inLine = inFile.readline()
        if not inLine:
            break
        inLine = inLine[:-1]
        name, phone, jersey = inLine.split(", ")
        team[name] = self(name, phone, jersey)
    print("Data Loaded Successfully.")
    inFile.close()
    return self

class teamClass:
    name = ""
    phone = 0
    jersey = 0

    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, name):
        return name

    def getPhone(self, phone):
        return phone

    def getJersey(self, jersey):
    return jersey

def displayData(team):
    print("\n")
    print("Welcome to the Team Manager")
    print("---------------------------")
    print("Name: ", team.name)
    print("Phone #: ", team.phone)
    print("Jersey #: ", team.jersey)
    print("\n")

def displayMenu():
    print("--------Main Menu--------")
    print("\n1. Display Team")
    print("2. Add Member")
    print("3. Remove Member")
    print("4. Edit Member")
    print("9. Exit Program")
    print("\n")

    return int(input("Selection: "))

def printTeam(team):
    if len(team) == 0:
        print("No team members in memory.")
    else:
        for x in team.keys():
            team.displayData()

def addTeam(team):
    newName = input("Enter the new player name: ")
    newPhone = input("Enter the phone #: ")
    newJersey = input("Enter the jersey #: ")

    team[newName] = teamClass(newName, newPhone, newJersey)

    return team

def removeTeam(team):
    removeName = input("Enter the member to be removed: ")
    if removeName in team:
        del team[removeName]
    else:
        print("Team member not found.")

    return team

def editTeam(team):
    oldName = input("Enter the player you want to edit: ")
    if oldName in team:
        newName = input("Enter the new name: ")
        newPhone = input("Enter the new phone number: ")
        newJersey = input("Enter the jersey #: ")
    else:
        print("Team member not found")

    return team

print("Welcome to the Team Manager") 
loadData() 
team = {}
menuSelection  displayMenu()

while menuSelection != 9:
    if menuSelection == 1:
        printTeam(team)
    elif menuSelection == 2:
        team = addTeam(team)
    elif menuSelection == 3:
        team = removeTeam(team)
    elif menuSelection == 4:
        team = editTeam(team)

    menuSelection = displayMenu()

saveData()

print("Exiting Program...")

I get this error once I add a member and try to display the dictionary:

Traceback (most recent call last):
  File "C:/Users/Gameradvocat3/PycharmProjects/Week6/Week6.py", line 121, in <module>
    printTeam(team)
  File "C:/Users/Gameradvocat3/PycharmProjects/Week6/Week6.py", line 83, in printTeam
    team.displayData()
AttributeError: 'dict' object has no attribute 'displayData'

Thank you all! I can not figure this out, this is for my Programming Essentials class. The only reason I am reaching out is because I have combed through the code and the literature from class and I can not figure out why this is not working.

Upvotes: 0

Views: 229

Answers (1)

Patrick Artner
Patrick Artner

Reputation: 51663

The class teamClass has no function displayData() you are calling printTeam() from your menu-screen with a dictionary of teamClass-objects:

def printTeam(team):
    if len(team) == 0:
        print("No team members in memory.")
    else:
        for x in team.keys():
            displayData(team[x])  # not team.displayData() - thats a class method call

In case you want to make it a class method you need to indent it and give it a first param of self but then other parts of your code need to be adjusted as the method currently is not fit to be a class-function.


I corrected all errors that hindered you from running this. The fixes are minimal effort on my side and lots of stuff could be made neater - ask on codereview for that. Look / ggogle / search SO for python csv - thats better for reading/writing csv data then what you did manually.

def saveData(team):
    filename = input("Filename to save: ")
    if not filename:                       # fix for non.input
        filename = "temp.csv"
    print("Saving Data...")
    with open(filename, "wt") as outFile:  # with paradigma for file
        for x in team.keys():
            name = team[x].name       # spelling error
            phone = team[x].phone     # spelling error
            jersey = team[x].jersey   # spelling error
            outFile.write(name + ", " + phone + ", " + jersey + "\n")
    print("Data saved.") 

def loadData():
    d = {}                                 # do not use self , you could buts bad habit
    filename = input("Filename to load: ")    
    if not filename:                       # if no name given, dont load, return empty 
        return {}
    with open(filename, "rt") as inFile:   # with paradig for open
        print("Loading data...")           # look into module csv
        while True:
            inLine = inFile.readline()
            if not inLine:
                break
            inLine = inLine[:-1]
            name, phone, jersey = inLine.split(", ")
            d[name] = teamClass(name, phone, jersey)
        print("Data Loaded Successfully.")
        return d

class teamClass:
    name = ""
    phone = 0
    jersey = 0

    def __init__(self, name, phone, jersey):
        self.name = name
        self.phone = phone
        self.jersey = jersey

    # youre not using getters/setters consistently so I removed them
    # def setName(self, name):
    #     self.name = name

    # your getters were wrong, fix like this:    
    # def getName(self):        # fix, getter needs no name
    #     return self.name      # fix missing self.


def displayData(player):       # renamed - not a team
    print("\n")
    print("Welcome to the Team Manager")
    print("---------------------------")
    print("Name: ", player.name)          
    print("Phone #: ", player.phone)
    print("Jersey #: ", player.jersey)
    print("\n")

def displayMenu():
    print("--------Main Menu--------")
    print("\n1. Display Team")
    print("2. Add Member")
    print("3. Remove Member")
    print("4. Edit Member")
    print("9. Exit Program")
    print("\n")


    try:                                   # catch errors
        return int(input("Selection: "))
    except:
        return -1                          # will lead to no action and reprint 

def printTeam(team):
    if len(team) == 0:
        print("No team members in memory.")
    else:
        for x in team.keys():
            displayData(team[x])           # fix -print each player of this team

def addTeam(team):
    newName = input("Enter the new player name: ")
    newPhone = input("Enter the phone #: ")
    newJersey = input("Enter the jersey #: ")

    team[newName] = teamClass(newName, newPhone, newJersey)

    return team

def removeTeam(team):
    removeName = input("Enter the member to be removed: ")
    if removeName in team:
        team.pop(removeName)    # remove with pop
    else:
        print("Team member not found.")

    return team

def editTeam(team):
    oldName = input("Enter the player you want to edit: ")
    if oldName in team:
        newName = input("Enter the new name: ")
        newPhone = input("Enter the new phone number: ")
        newJersey = input("Enter the jersey #: ")
        team.pop(oldName)                                        # remove old
        team[newName] = teamClass(newName, newPhone, newJersey)  # add new
    else:
        print("Team member not found")

    return team


print("Welcome to the Team Manager")  
team = loadData() 
menuSelection = displayMenu()             # = missing
while menuSelection != 9:
    if menuSelection == 1:
        printTeam(team)
    elif menuSelection == 2:
        team = addTeam(team)
    elif menuSelection == 3:
        team = removeTeam(team)
    elif menuSelection == 4:
        team = editTeam(team)

    menuSelection = displayMenu()

saveData(team)                           # data missing

print("Exiting Program...")

Upvotes: 1

Related Questions