0

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.

6
  • displayData is a function that takes team as an argument, not a method of the dict class. You want displayData(team). Commented Jan 18, 2018 at 22:33
  • You have a displayData() function: displayData(team). Commented Jan 18, 2018 at 22:33
  • 1
    There are quite a few more problems in this code, I'm afraid. Commented Jan 18, 2018 at 22:35
  • Do you guys have any input as to what I need to change? I have been battling with this for 3 days now :( Commented Jan 19, 2018 at 3:04
  • I said that in complete knowledge that I sound clueless, Python isn't a language I have messed with before. Any help would be greatly appreciated @MartijnPieters Commented Jan 19, 2018 at 3:24

1 Answer 1

1

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...")
Sign up to request clarification or add additional context in comments.

5 Comments

How would I go about adjusting my existing code? I tried this but I still get the same error about it not being an attribute of the dict object.
@ChaseQuinn a dictionary has data that is accessable by keys. You give the whole dict into printTeam(), you iterate over its keys for x in team.keys(): and use displayData( .. ) which takes a team as input. To get from the key to the data you use dict[key] :displayData(team[x]). Sorry for the 4h delay, right now its 8am here - fixed the code above
I tried this but for some reason I can not get it to work with that code. I am an absolute novice here :(
@ChaseQuinn as MartijnPieters commented, lots of problems. I made patches for most of them, the code should be runnable now.
Thank you so much! I can actually see my errors and I understand why it wasn't working! Java is a little different and I couldn't wrap my head around this for some reason. Thank you again!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.