This is the function defined in class "Roster"
class Roster:
def __init__(self, name, phone, jersy):
self.name = name
self.phone = phone
self.jersy = jersy
def setName(self, name):
self.name = name
def setPhone(self, phone):
self.phone = phone
def setnumber(self, jersy):
self.number = jersy
def getName(self):
return self.name
def getPhone(self):
return self.phone
def getNumber(self):
return self.jersy
def displayMenu(self):
print ("==========Selection Menu==========")
print ("1. Display the Roster")
print ("2. Add a Player to the Roster")
print ("3. Remove a Player from the Roster")
print ("4. Change a Player Name displayed in the Roster")
print ("5. Load the Roster")
print ("6. Save the Roster")
print ("7. Quit")
print ()
return int (input ("Selection>>> "))
def displayRoster(self):
print ("****Team Roster****")
print ("Player's Name:", self.name)
print ("Player's Telephone number:", self.phone)
print ("Player's Jersey number:", self.jersy)
This is the code:( I understand that you don't have to "Import" a class into itself so there is no Import call)
Players = {}
def addPlayer(Players):
newName = input ("Add a player's Name: ")
newPhone = input ("Phone number: ")
newNumber = input ("Jersey number: ")
Players[newName] = newName, newPhone, newNumber
return Players
def removePlayer(Players):
removeName = input ("What name would you like to remove? ")
if removeName in Players:
del Players[removeName]
else:
print ("Name was not found!")
return Players
def editPlayer(Players):
oldName = input ("What name would you like to change? ")
if oldName in Players:
newName = input ("What is the new name? ")
newPhone = input ("Phone number: ")
newNumber = input ("Jersey number: ")
Players[newName] = newName, newPhone, newNumber
del Players[oldName]
print ("***", oldName, "has been changed to", newName)
else:
print ("Name was not found!")
return Players
def saveRoster(Players):
print("Saving data...")
outFile = open("D:\Documents\Grantham\Python Projects\Python Week Six\Roster.txt", "wt")
for x in Players.keys():
name = Roster.getName(Players)
phone = Roster.getPhone(Players)
jersy = Roster.getNumber(Players)
outFile.write("name+","+phone+","+jersy+","\n")
print("Data saved.")
outFile.close()
return Players
def loadRoster():
Players = {}
filename = input("Filename to load: ")
inFile = open(Filename(Players), "rt")
print("Loading data...")
while True:
inLine = inFile.readline()
if not inLine:
break
inLine = inLine[:-1]
name, phone, jersy = inLine.split(",")
Players[name] = RosterClass.Players(name, phone, jersy)
print("Data Loaded Successfully.")
inFile.close()
return Players
print ("Welcome to the Team Manager")
menuSelection = Roster.displayMenu ('Players')
while menuSelection != 7:
if menuSelection == 1:
myRoster.displayRoster (Players)
elif menuSelection == 2:
Players = addPlayer (Players)
elif menuSelection == 3:
Players = removePlayer (Players)
elif menuSelection == 4:
Players = editPlayer (Players)
elif menuSelection==5:
loadRoster(Players)
elif menuSelection==6:
saveRoster(Players)
menuSelection = Roster.displayMenu (Players)
print ("Exiting Program...")
I keep getting this error:
Traceback (most recent call last):
File ".idea/Adv Team Roster.py", line 108, in <module>
Roster.displayRoster ('Players')
File ".idea/Adv Team Roster.py", line 39, in displayRoster
print ("Player's Name:", self.name)
AttributeError: 'str' object has no attribute 'name'
I'm also having problems with the save/load routine but that's another post.
Your code has a number of conceptual problems that you need to solve before you can start trying to run it and start asking for help with compiler errors. Here are three, to get you started.
(1) Your Roster class is designed to be instantiated, but you never create an instance. Whenever you write a class, among the early questions you should ask yourself are, "What code will create instances of this class? Under what circumstances? How will that code get the data it needs to create an instance? What will that code do with the instance right after it has created the instance?"
(2) Your Roster class is misnamed, which is probably confusing you. A roster is a list of players. Your Roster is data about a single player. I recommend renaming Roster to Player, creating some data structure (like your current Players) called roster to hold a bunch of players, and then following the consequences of that change.
(3) Once you have a clear idea of what rosters and players are, you can ask questions like, "Where will I store rosters and players? How will I pass them around to different parts of my code? What functionality should be associated with a roster? with a player? with the top level of my code? with other entities that I haven't thought about yet?"
After all that thinking, you might come the conclusion that displayPlayer should be a function on the Player class and that you therefore need to rename displayRoster to displayPlayer. Since you will have created instances of Player, perhaps one called myplayer (that's just an example name), you will now be able to say myplayer.displayPlayer(), and Python will run the displayPlayer code with self automatically set to the myplayer instance. At that point the compiler error you are complaining about will disappear, not because you "fixed" it, but because it naturally goes away once you are thinking clearly about your system.
And in general, that is the way to think about compiler errors: If it's not immediately obvious how to fix it, then it's probably a sign that you aren't thinking clearly about your system, so you need to take a step back and think about higher-level problems than the specific error.
Related
This code is a Simple Student Management System in which I want it to receive inputs from the user and display according to the call. I have created a class Student and initialized the variables. I created a method accept(self) for receiving the user inputs and appending the details to a list of dictionaries. But I am stuck on how I can initialize the inputs that I have received. How can I call the methods outside of class Student since I am unable to create an object for class Student? I am a beginner in Python. Having a hard time understanding OOP. Please help me!
Here is the code I wrote:
class Student:
student_details = []
def __init__(self, name, rollno, mark1, mark2):
self.name = name
self.rollno = rollno
self.mark1 = mark1
self.mark2 = mark2
def accept(self):
no_of_entries = int(input("Enter the number of entries: "))
i = 1
while i <= no_of_entries:
print(f"Student {i}")
name = input("Name: ")
rollno = int(input("Roll: "))
mark1 = int(input("Mark 1: "))
mark2 = int(input("Mark 2: "))
Student(name, rollno, mark1, mark2).student_details.append({
"Name": self.name,
"Rollno": self.rollno,
"Mark1": self.mark1,
"Mark2": self.mark2,
})
print()
i += 1
print(Student.student_details)
student1 = Student()
proceed = True
while proceed:
print("STUDENT MANAGEMENT SYSTEM".center(50, '-'))
print()
print("* Accept Student entries (1): ")
print("* Search Student entries (2): ")
print("* Update Student entries (3): ")
print("* Delete Student entries (4): ")
print("* Display Student entries (5): ")
choice = int(input("Enter your choice: "))
if choice == 1:
I get the error:
Student.__init__() missing 4 required positional arguments: 'name', 'rollno', 'mark1', and 'mark2'
I don't know what to do. Even this is the problem I am facing with OOP in Python. If anyone can help me with this than I will be grateful
EDIT: The callback comes from the student1 = Student()
delete the statement and declare the accept method as a static method.
Then you can deklare a student in the method and can appent the student.
Your mistake should be here:
Student(name, rollno, mark1, mark2).student_details.append({
"Name": self.name,
"Rollno": self.rollno,
"Mark1": self.mark1,
"Mark2": self.mark2,
})
You try to initialise a object and then you try to use it as a dict.
st1 = Student(name, rollno, mark1, mark2)
Student.student_details.append(st1)
Also you can use a classattribut in a object but the changes will only be present in the object. It wouldnt be in all object.
It would be best make the method accept in a function or you will end up with many object with the same values.
If you want to leave it as a method you can change the code to:
Student.student_details.append(self)
By default methods defined in a Python class are instance methods, so they need to be called on an already-existing object instance. If you want to create a custom constructor, the method should be probably marked as a class method by using #classmethod decorator, so it can be called on the class itself.
class Student:
student_details = []
def __init__(self, name, rollno, mark1, mark2):
self.name = name
self.rollno = rollno
self.mark1 = mark1
self.mark2 = mark2
#classmethod
def accept(cls):
no_of_entries = int(input("Enter the number of entries: "))
for i in range(no_of_entries):
print(f"Student {i}")
name = input("Name: ")
rollno = int(input("Roll: "))
mark1 = int(input("Mark 1: "))
mark2 = int(input("Mark 2: "))
student = cls(name, rollno, mark1, mark2)
cls.student_details.append(student)
print(cls.student_details)
Student.accept()
student1 = Student()
you need to pass 4 parameters here
def __init__(self, name, rollno, mark1, mark2):
So you should have
student1 = Student('name', 'rollno', 'mark1', 'mark2')
or something
You forgot to put arguments when you call that class.
For example:
student1 = Student(name='a', rollno='0', mark1='1', mark2='2')
I'm not sure what your objective is. If you just want to input student information into a list, maybe the code below can give you an idea.
class Student:
student_details = []
def __init__(self, name, rollno, mark1, mark2):
self.name = name
self.rollno = rollno
self.mark1 = mark1
self.mark2 = mark2
student_list = []
print("STUDENT MANAGEMENT SYSTEM".center(50, '-'))
print()
print("* Accept Student entries (1): ")
print("* Search Student entries (2): ")
print("* Update Student entries (3): ")
print("* Delete Student entries (4): ")
print("* Display Student entries (5): ")
choice = int(input("Enter your choice: "))
if choice == 1:
print("You have selected (1) - Accept Student entries")
no_of_entries = int(input("Enter the number of entries: "))
for i in range(0, no_of_entries):
print("Input student no", i+1, "information.")
student = Student(name=input("Name: "), rollno=input("Roll: "), mark1=input("Mark 1: "), mark2=input("Mark 2: "))
student_list.append(student)
elif choice == 2:
pass
elif choice == 3:
pass
elif choice == 4:
pass
elif choice == 5:
pass
else:
print("Invalid choice.")
Below is my code for a class I am currently working. The title contains the errors I am receiving. Could someone please assist with my code? (The comment's explain the area of concern. Main Menu functions 5 & 6.)
PART 1 - CLASS ESTABLISHMENT
class MemberClass:
name = ""
phone = 0
number = 0
# Initiator Method
def __init__(self, name, phone, number):
self.name = name
self.phone = phone
self.number = number
# Mutator Method 1
def set_name(self, name):
self.name = name
# Mutator Method 2
def set_phone(self, phone):
self.phone = phone
# Mutator Method 3
def set_number(self, number):
self.number = number
# Accessor Method 1
def get_name(self):
return self.name
# Accessor Method 2
def get_phone(self):
return self.phone
# Accessor Method 3
def get_number(self):
return self.number
# Display Method
def display_data(self):
print("")
print("Current Team Member's Information")
print("------------------------------------------------")
print("Member's Name: ", self.name)
print("Member's Phone Number: ", self.phone)
print("Member's Jersey Number: ", self.number)
print("------------------------------------------------")
PART 2 - PROGRAM FUNCTIONS AND DATA
# Create a function for the main menu
def print_menu():
print("===========Main Menu===========")
print("1. Display Current Team Roster.")
print("2. Add Member.")
print("3. Remove Member.")
print("4. Edit Member.")
print("5. Save Progress.")
print("6. Load Current Team Roster")
print("9. Exit Program.\n")
return int(input("Please Enter Your Selection: "))
# Create a function for main menu option 1
def print_members(team_members):
if len(team_members) == 0:
print("No Current Team Members In Memory! Please Add All Team Members.")
else:
for x in team_members.keys():
team_members[x].display_data()
# Create a function for main menu option 2
def add_members(team_members):
new_name = input("Enter New Team Member's Name: ")
new_phone = int(input("Enter New Team Member's Phone Number: "))
new_number = int(input("Enter New Team Member's Jersey Number: "))
team_members[new_name] = MemberClass(new_name, new_phone, new_number)
return team_members
# Create a function for main menu option 3
def remove_members(team_members):
remove_name = input("Enter Existing Team Member's Name to Remove: ")
if remove_name in team_members:
del team_members[remove_name]
print("The Team Member ("+remove_name+") Is No Longer In Our Roster.")
else:
print("The Provided Name ("+remove_name+") Is Not Currently In Our Roster. Please Try Again.")
return team_members
# Create a function for main menu option 4
def edit_members(team_members):
original_name = input("Enter Existing Team Member's Name To Edit: ")
if original_name in team_members:
adjusted_name = input("Enter Existing Team Member's Updated Name: ")
adjusted_phone = int(input("Enter Existing Team Member's Updated Phone Number: "))
adjusted_number = int(input("Enter Existing Team Member's Updated Jersey Number: "))
del team_members[original_name]
team_members[original_name] = MemberClass(adjusted_name, adjusted_phone, adjusted_number)
else:
print("The Provided Name ("+original_name+") Is Not Currently In Our Roster. Please Try Again.")
return team_members
# Create a function for main menu option 5 ***PROBLEM AREA***
def save_members(members, filename):
out_file = open(filename, "wt")
with open(filename, "wt") as out_file:
for name, phone, number in members.items():
out_file.write(name + "," + phone + "," + number + "\n")
# Create a function for main menu option 6 ***PROBLEM AREA***
def load_members(members, filename):
in_file = open(filename, "rt")
with open(filename, "rt") as in_file:
while True:
in_line = in_file.readline()
if not in_line:
break
in_line = in_line[:-1]
name, phone, number = in_line.split(",")
members[name] = phone
PART 3 - PROGRAM ROOT CODE
# Team manager welcome screen, date & time
print("Welcome to San Angelo's Softball Team Roster")
print("This program keeps the most up-to-date information")
print("Today's Date: April 23, 2018")
print("Current Time: 0900\n")
# Create a dictionary named "team_members"
team_members = {}
# Provides Menu Screen
menu_selection = print_menu()
# Create while loop repeating the main menu.
while menu_selection != 9:
if menu_selection == 1:
print_members(team_members)
elif menu_selection == 2:
team_members = add_members(team_members)
elif menu_selection == 3:
team_members = remove_members(team_members)
elif menu_selection == 4:
team_members = edit_members(team_members)
elif menu_selection == 5:
filename = input("Enter Desired Filename: ")
save_members(team_members, filename)
elif menu_selection == 6:
filename = input("Enter Existing Filename: ")
load_members(team_members, filename)
menu_selection = print_menu()
print("Thank You For Updating San Angelo's Softball Team Roster!")
When you iterate a dictionary via dict.items, you may only iterate key / value pairs. Therefore, this line will fail as you are attempting to unpack 3 items when only 2 exist (key & value):
for name, phone, number in members.items():
Instead, what you should do:
for name, myclass in members.items():
phone = myclass.phone
number = myclass.number
I am trying to allow a member to leave the Team if they so wish. By doing this, the system will delete them and their user ID will become available to the next person who wishes to join the team. I am receiving an error with my code. Can someone please advise what I am doing wrong and how this can be achieved?
I would like my add members and remove members to update all the time, based on user input and the needs of the members. I hope this makes sense!
For example: If 'Carl' decided to leave, he would be removed and the next member to join would be assigned the membership ID '2'
Below is my code:
all_users = []
class Team(object):
members = []
user_id = 0
def __init__(self, first, last, address):
self.user_id = Team.user_id
self.first = first
self.last = last
self.address = address
self.email = first + '.' + last + '#python.com'
Team.user_id += 1
Team.members.append(self)
def __str__(self):
print()
return 'Membership ID: {}\nFirst Name: {}\nSurname: {}\nLocation: {}\nEmail: {}\n'.format(self.user_id,
self.first, self.last,
self.address,
self.email)
print()
#staticmethod
def all_members():
for user in all_users:
print(user)
#staticmethod
def add_member():
print()
print("Welcome to the team!")
print()
first_name = input("What's your first name?\n")
second_name = input("What's your surname?\n")
address = input("Where do you live?\n")
all_users.append(Team(first_name, second_name, address))
#staticmethod
def remove_member():
print()
print("We're sorry to see you go , please fill out the following information to continue")
print()
first_name = input("What's your first name?\n")
second_name = input("What's your surname?\n")
address = input("Where do you live?\n")
unique_id = input("Finally, what is your User ID?\n")
if unique_id in all_users:
del unique_id
all_users(User(first_name, second_name, address))
def main():
user_1 = Team('Chris', 'Parker', 'London')
user_2 = Team('Carl', 'Lane', 'Chelsea')
all_users.extend([user_1, user_2])
continue_program = True
while continue_program:
print("1. View all members")
print("2. Want to join the team?")
print("3. Need to leave the team?")
print("3. Quit")
try:
choice = int(input("Please pick one of the above options "))
if choice == 1:
Team.all_members()
elif choice == 2:
Team.add_member()
elif choice == 3:
Team.remove_member()
elif choice == 4:
continue_program = False
print()
print("Come back soon! ")
print()
else:
print("Invalid choice, please enter a number between 1-3")
main()
except ValueError:
print()
print("Please try again, enter a number between 1 - 3")
print()
if __name__ == "__main__":
main()
The remove_member method is wrong for several reasons. The line del unique_id will not remove the value from all_users, which is just a list of Team Members. And you shouldn't have to ask the user for all of this information - just the ID (or the name) would be enough.
What I suggest is:
#staticmethod
def remove_member():
print()
print("We're sorry to see you go , please fill out the following information to continue")
print()
unique_id = input("what is your User ID?\n")
unique_id = int(unique_id)
for i, user in enumerate(all_users):
if user.user_id == unique_id:
all_users.remove(i)
break
If it is important that the user ids are reused, you can keep a list of user ids that are available again. When creating a new member, you can first check that list, and use an old id if there is one.
You can also choose not to reuse the user ids of removed users. An id doesn't really have a meaning and not reusing it makes it simpeler for you.
Finally, you might want to restructure your code:
Team(first_name, second_name, address)
This doesn't make sense: a team with a first name, last name and adress! Better would be to have two classes:
team = Team()
user = User(first_name, second_name, address)
team.add_member(user)
team.remove_member(user)
Some other tips:
# This won't work, because all_users contains Team instances, not numbers. So the user will never be found.
if unique_id in all_users:
# This won't do anything: `del` only removes the access to the variable (might free up memory in heavy applications). It doesn't remove the user from all_users
del unique_id
I am trying to create a simple database on python that:
- Add a record, delete a record, report on the database
(I am very new to this program and programming in general)
*NOTE: I am aware there are programs like SQL but my professor wants us to create a a database simply with what we learned in class *
I am having serious trouble on being able to store: ID, Class Name, and Class instructor
into one record of "Classes". I have been able to display the class ID and class name but I'm not sure how to add an instructor's name.
This is what I have currently:
def print_menu():
print('1. Print Class Records')
print('2. Add a Class')
print()
classes = {}
menu_choice = 0
print_menu()
while menu_choice != 5:
menu_choice = int(input("Type in a number (1-5): "))
if menu_choice == 1:
print("Class Reports:")
for x in classes.keys():
print("Class ID: ", x, "\tClass Name:", classes[x], "\tClass Instructor:",)
print()
elif menu_choice == 2:
print("Add ClassID, Class Name, and Instructor Name")
classID = input("ID: ")
className = input("Class Name: ")
classInst = input("Class Instructor: ")
classes[classID] = className
elif menu_choice != 5:
print_menu()
I feel that I will be able to do the rest of the professor's requirements for this project but I have been stuck on this part for days with no response from my professor
I would highly appreciate quick responses as this assignment is due tonight at 11:59 and I am reaching out for help here as a last resort.
Thank you!
In your case, what you can do is, insert the ID as a key for each class and then insert a dictionary as it's value. What I mean by this is that each key on the classes dict, points to another dictionary as its value.
elif menu_choice == 2:
print ("Add ClassID, Class Name, and Instructor Name")
classID = input("ID: ")
className = input("Class Name: ")
classInst = input("Class Instructor: ")
classes[classID] = {"className" : className, "classInst" : classInst}
and printing the values as
print("Class ID: ", x , "\tClass Name:" , classes[x]["className"] , "\tClass Instructor:" , classes[x]["classInst"])
The purpose of the two programs is to have twitter.py manage tweet.py by having the 5 most recent tweets that are saved in the program twitter.py to show up once you search and find it. There are four options, make a tweet, view recents tweets, search a tweet and quit. I'm having trouble saving because it keeps saying no recent tweets are found. Also I'm having trouble with the fact that I can't search for my tweets but that is probably the same reason as my first problem because they aren't being saved correctly. Thank you please help!!
tweet.py
import time
class tweet:
def __init__(self, author, text):
self.__author = author
self.__text = text
self.__age = time.time()
def get_author(self):
return self.__author
def get_text(self):
return self.__text
def get_age(self):
now = time.time()
difference = now - self.__time
hours = difference // 3600
difference = difference % 3600
minutes = difference // 60
seconds = difference % 60
# Truncate units of time and convert them to strings for output
hours = str(int(hours))
minutes = str(int(minutes))
seconds = str(int(seconds))
# Return formatted units of time
return hours + ":" + minutes + ":" + seconds
twitter.py
import tweet
import pickle
MAKE=1
VIEW=2
SEARCH=3
QUIT=4
FILENAME = 'tweets.dat'
def main():
mytweets = load_tweets()
choice = 0
while choice != QUIT:
choice = get_menu_choice()
if choice == MAKE:
add(mytweets)
elif choice == VIEW:
recent(mytweets)
elif choice == SEARCH:
find(mytweets)
else:
print("\nThanks for using the Twitter manager!")
save_tweets(mytweets)
def load_tweets():
try:
input_file = open(FILENAME, 'rb')
tweet_dct = pickle.load(input_file)
input_file.close()
except IOError:
tweet_dct = {}
return tweet_dct
def get_menu_choice():
print()
print('Tweet Menu')
print("----------")
print("1. Make a Tweet")
print("2. View Recent Tweets")
print("3. Search Tweets")
print("4. Quit")
print()
try:
choice = int(input("What would you like to do? "))
if choice < MAKE or choice > QUIT:
print("\nPlease select a valid option.")
except ValueError:
print("\nPlease enter a numeric value.")
return choice
def add(mytweets):
author = input("\nWhat is your name? ")
while True:
text = input("what would you like to tweet? ")
if len(text) > 140:
print("\ntweets can only be 140 characters!")
continue
else:
break
entry = tweet.tweet(author, text)
print("\nYour tweet has been saved!")
def recent(mytweets):
print("\nRecent Tweets")
print("-------------")
if len(mytweets) == 0:
print("There are no recent tweets. \n")
else:
for tweets in mytweets[-5]:
print(tweets.get_author, "-", tweets.get_age)
print(tweets.get_text, "\n")
def find(mytweets):
author = input("What would you like to search for? ")
if author in mytweets:
print("\nSearch Results")
print("----------------")
print(tweet.tweet.get_author(), - tweet.tweet.get_age())
print(tweet.tweet.get_text())
else:
print("\nSearch Results")
print("--------------")
print("No tweets contained ", author)
def save_tweets(mytweets):
output_file = open(FILENAME, 'wb')
pickle.dump(mytweets, output_file)
output_file.close()
main()
In twitter.py:add_tweets, mytweets is passed into the function and entry is created, but it is never added to mytweets. The created entry is lost after the function returns.
Your question was:
I'm having trouble saving because it keeps saying no recent tweets are
found.
Function add does not seem to be adding tweets anywhere. It creates a tweet.tweet instance, but it does not do anything with it.
You probably want to add the tweet to mytweets?
Another problem:
You initialize mytweets as a dicionary (tweet_dct = {}), but later you use it as a list (mytweets[-5]). It should be a list from start. And you probably want last five tweets (mytweets[-5:]), not just the fifth from the end.
On the sidenotes:
What you have here is not "two programs" - it is one program in two python files, or "modules"
Although there is nothing wrong with having getters (functions like get_author), there is no need for them in Python (see How does the #property decorator work?). Do youself a favour and keep it simple, e.g.:
class Tweet:
def __init__(self, author, text):
self.author = author
self.text = text
self.creation_time = time.time()
def get_age_as_string(self):
# your code from get_age
There will be time when you need private variables. When that happens, use a single leading underscore (self._author) until you fully understand what double underscore does and why.
Pickle is probably not the best way to store information here, but it is a good start for learning.