I'm trying to solve this problem on my own. The problem asks to write a class for employee information, then ask user to input that information, and finally print the entered information.
I want to use two for loops, one for getting information and one for printing the information. Unfortunately, the printing for loop does not working.
class Employee:
def __init__(self, name, id_num, department, job):
self.__name = name
self.__id_num = id_num
self.__department = department
self.__job = job
# setters
def set_name(self,name):
self.__name = name
def set_id(self,id_num):
self.__id_num = id_num
def set_department(self,department):
self.__department = department
def set_job(self,job):
self.__job = job
# getters
def get_name(self):
return self.__name
def get_id(self):
return self.__id_num
def get_department(self):
return self.__department
def get_job(self):
return self.__job
def main():
employee_list = []
for i in range(2):
name = input('What is the name of the employee? ')
id_num = float(input('What is the ID number of the employee? '))
department = input('What is the department where the employee works? ')
job = input('What is the job title of the empoyee? ')
personnel = Employee(name,id_num,department,job)
employee_list.append(personnel)
return employee_list
for item in employee_list:
print(item.get_name())
print(item.get_id())
print(item.get_department())
print(item.get_job())
print()
main()
You need to remove the following line in your main() function:
return employee_list
It is causing your main to stop running without ever reaching the printing for loop.
Related
new to python , trying to learn oops ,
in below code my objective is to sort employee list based on rating but stuck at object not iteratable.
class Employee:
def getfn(self):
self.empid=(input(" enter emp id:"))
self.name=input("enter name:")
self.gender=input("enter emp gender: ")
self.salary=input(" enter emp salary:")
self.rating=int(input("enter rating:"))
empz=[]
class menu:
n=0
def entry(self):
n=int(input(" enter no of employees:"))
i=0
while i<n:
temp_emp=Employee()
temp_emp.getfn()
empz.append(temp_emp)
i+=1
def print_rec(self):
#
print("-id--name--gender--salary--rating--")
for i in empz:
print(i.empid,i.name,i.gender,i.salary,i.rating)
#print(sorted(empz,key=lambda x:x[4]))
def sort_rating(empz):
return empz.rating
sorted_emp=sorted(empz, key= sort_rating)
print(empz)
The design of your Employee class isn't great. Values used as its attributes should be validated before class construction.
You can control the number of employees to be input more easily than asking for a count.
Hopefully this will give a better idea of how this might be done.
class Employee:
def __init__(self, empid, name, gender, salary, rating):
self.empid = empid
self.name = name
self.gender = gender
self.salary = salary
self.rating = rating
def __str__(self):
return f'ID={self.empid}, Name={self.name}, Gender={self.gender}, Salary={self.salary}, Rating={self.rating}'
# common input functions
def getInput(prompt, t=str):
while True:
v = input(f'{prompt}: ')
try:
return t(v)
except ValueError:
print('Invalid input')
def getInt(prompt):
return getInput(prompt, int)
def getFloat(prompt):
return getInput(prompt, float)
# end of common input functions
employeeList = []
while eid := getInput('ID (Enter to finish)'):
name = getInput('Name')
gender = getInput('Gender')
salary = getFloat('Salary')
rating = getInt('Rating')
employeeList.append(Employee(eid, name, gender, salary, rating))
for employee in sorted(employeeList, key=lambda x: x.rating):
print(employee)
The common input functions should be in a separate py file so you can import them when needed rather than re-writing them every time. They're trivial but you'll find them helpful when trying to ensure that input is appropriate
Disregard the naming conventions as to what class is part of which it is just a test run.
I need some help with the OOP inheritance i have created a class of Students, Teachers, and the principal. My goal is for the principal to be able to add employees. The problem is i just want to use a for loop to get the names and then pass that method as an attribute for the principal object. i was able to do it with the class Input without the self parameter. can someone tell me
what is going on here and how can i fix this with self. i removed input from names so that my question wont get shut down
class Input:
def count():
cnt = []
for i in range(4):
name = ('Enter name here: ')
cnt.append(name)
return cnt
class Student:
def __init__(self,name,lastname):
self.name = name
self.lastname = lastname
class StudentCouncil(Student):
def __init__(self, name, lastname, tenure):
super().__init__(name,lastname)
self.tenure = tenure
class Principal(StudentCouncil):
def __init__(self, name, lastname, tenure,employees=None):
super().__init__(name,lastname,tenure)
if employees is None:
self.employees = []
else:
self.employees = employees
def display(self):
for names in self.employees:
print(names,end=' ')
count = Input.count()
tij = Principal('Mike','Thoma','3',count)
tij.display()
If the method takes a self parameter, you need to create an instance of the class. So it would be:
class Input:
def count(self):
cnt = []
for i in range(4):
name = input('Enter name here: ')
cnt.append(name)
return cnt
and then you would do:
myinput = Input()
count = myinput.count()
Your count() method doesn't use any attributes of self, so it doesn't currently need to be written this way. But you might want to redefine it like this:
class Input:
def __init__(self, howmany):
self.howmany = howman
def count(self):
return [input('Enter name here: ') for _ in range(self.howmany)]
myinput = Input(4)
count = myinput.count()
If count is all you want from Input, just make it a function:
def input_names():
cnt = []
for i in range(4):
name = ('Enter name here: ')
cnt.append(name)
return cnt
If you want a configurable Input type of some sort, then you want to run count on an instance of that, you need self:
class Input:
def count(self):
cnt = []
for i in range(self.num_names): # if we need some configuration
name = ('Enter name here: ')
cnt.append(name)
return cnt
Else, the kosher way to do this is to use the staticmethod decorator:
class Input:
#staticmethod
def count():
cnt = []
for i in range(4):
name = ('Enter name here: ')
cnt.append(name)
return cnt
Your current code will work as you use it currently, Input.count(), but if you instantiated an input, Input().count() would throw an exception. The staticmethod decorator ensures that this method is safe to call on either the class directly or on an instance of that class.
Here is what i have so far
from CSE_324_course import Course
from CSE_324_skeleton_student import Student
math = Course("Algebra I")
language = Course("Spanish I")
science = Course("Earth Science")
history = Course("U.S. History I")
phys_ed = Course("Physical Education I")
speaking = Course("Speech I")
art = Course("Art I")
test_student = Student("Jill", "Sample")
test_student.add_course(math)
test_student.add_course(language)
test_student.add_course(science)
test_student.add_course(history)
test_student2 = Student("Bill", "Sample")
test_student2.add_course(math)
test_student2.add_course(phys_ed)
test_student2.add_course(science)
test_student2.add_course(history)
test_student3 = Student("Kim", "Sample")
test_student3.add_course(language)
test_student3.add_course(speaking)
test_student3.add_course(science)
test_student3.add_course(art)
student_list=[test_student,test_student2,test_student3]
for (test_student,test_student2,test_student3 : get_course)
if (test_student().equals(search))
System.out.println(teststudnetgetCourse());
#Each iteration should:
#get,concatenate, and print the first and last name of the student
#print all courses for that student
#print a blank line between students
'''for this part you may need to review the other skeleton code to:
- see how to get items from a list
- see if there is code (like a function) in that file you can call in this file
- verify that running this file gets you the correct output with information from that file
Also, review syntax of pulling items from a list f
2 page of code
Course import Course
class Student:
student_id = 0
def __init__(self, first_name, last_name):
self.first_name = first_name
self.last_name = last_name
self.courses = []
self.student_id = Student.student_id
Student.student_id += 1
def __str__(self):
# TODO You will need to use a variable in the loop, so you must intialize it here,
# that variable will need to be initalized to get items listed in the first def _init_ section
# TODO add a loop that will go through the course list
# TODO Add code here to create a string representation of a student,
# including first and last name and all courses that student is taking
return "complete this return statement based on your in loop variable"
def get_first_name(self):
return self.first_name
def get_last_name(self):
return self.last_name
def get_student_id(self):
return self.student_id
def add_course(self, new_course):
# TODO add code to append new_course to self.courses
print "Course not yet added, implementation needed."
3rd page
class Course:
def __init__(self, course_name):
self.course_name = course_name
def __str__(self):
return self.course_name
I think you are looking to change
for (test_student,test_student2,test_student3 : get_course)
if (test_student().equals(search))
System.out.println(teststudnetgetCourse());
(which you have improperly indented) to:
for student in student_list:
print("{} {}".format(student.first_name, student.last_name))
for course in student.courses:
print(course) # This won't work because "2 page of code Course import Course" needs to be finished
print("\n") # blank line between students
This question already has answers here:
How to print instances of a class using print()?
(12 answers)
Closed 4 years ago.
import employee
def main():
print('This program will create employee objects and store their information')
print()
ledger = []
numOfEmployees = int(input("Enter the number of employee's to enter: "))
for count in range(numOfEmployees):
name = input("Enter employee's name: ")
id_number = input("Enter employee's ID number: ")
department = input("Enter employee's department: ")
job_title = input("Enter employee's job title: ")
count = employee.Employee(name, id_number, department, job_title)
ledger.append(count)
print("This is the list of employee's:")
for person in ledger:
print(person)
main()
the following is my employee module. I know making the ledger inside the module would make more sense but it seems like I should probably figure out how to do it an easier way before I try implementing that.
class Employee:
def __init__(self, name, id_number, department, job_title):
self.__name = name
self.__id_number = id_number
self.__department = department
self.__job_title = job_title
def set_name(self, name):
self.__name = name
def set_id_number(self, id_number):
self.__id_number = id_number
def set_department(self, department):
self.__department = department
def set_job_title(self, job_title):
self.__job_title = job_title
def get_name(self):
return self.__name
def get_id_number(self):
return self.__id_number
def get_department(self):
return self.__department
def get_job_title(self):
return self.__job_title
the following is the output.
This program will create employee objects and store their information
Enter the number of employee's to enter: 1
Enter employee's name: adf
Enter employee's ID number: afd
Enter employee's department: asdf
Enter employee's job title: asdf
This is the list of employee's:
<employee.Employee object at 0x000001A96A92FF98>
I want it to actually print out the values and not just its location in memory... How can I do this?
To print objects, you need to supply a definition for what their string representation is. And then, you describe that in the __str__() override:
For example, yours could be something like:
class Employee
... # other functions
def __str__(self):
return "{}, {}, {}".format(self.__name, self.__id_number, self.__department)
Obviously, you can decide to format it however you want.
Also, you should look up #property decorators so you don't need to make your own getters and setters, but that's aside from your question.
Define a __str__ method for your object. This method is automatically called by Python when the object is used in a context where a string is expected (typically, print).
E.g.:
class Employee:
def __str__(self):
return self.__name
I'm taking my first Python class so please bear with me, I have ZERO experience in programming but I'm very eager to learn. If you could steer me in the right direction I'd really appreciate it. Thank you in advance.
I've looked through previous questions but I wasn't able to find one that fully helped/explained where I'm getting stuck. I have a dictionary that stores team members(names, phone, jersey) and need to be able to write this to a file. Below is what I currently have, when I run this I get the error AttributeError:'dict' object has no attribute 'getname'.
class Member:
def get name(self):
return self.name
def get phone(self):
return self.phone
def get jersey(self):
return self.jersey
members={}
def saveData(members, filename):
filename=input("Filename to save:")
outFile=open(filename,"wt")
for x in members.keys():
name=members[x].getname
phone=members[x].getphone
jersey=members[x].getjersey
outFile.write(name+","+phone","+jersey+"\n")
print("Data Saved")
outFile.close()
Member class
You've put a space in the function name, so it won't work.
Too, you don't seem to have an __init__ function.
class Member:
def __init__(self, name, phone, jersey):
self.name = name
self.phone = phone
self.jersey = jersey
def get_name(self):
return self.name
def get_phone(self):
return self.phone
def get_jersey(self):
return self.jersey
Anyway, it's a lot easier that just don't make these get functions; the user can get the variables of a class using the dot syntax.
class Member:
def __init__(self, name, phone, jersey):
self.name = name
self.phone = phone
self.jersey = jersey
shell:
>>> member1 = Member("Dave", "123456789", "red")
>>> member.name
'Dave'
>>> member.phone
'123456789'
>>> member.jersey
'red'
saveData function
It won't work, you should do this:
def saveData(members): # don't include filename, it's going to be redefined later
filename = input("Filename to save: ") # space at the end
with open(filename, 'wt') as outFile: # using with for files is recommended
# then you don't need to close the file
for x in members: # you can directly iterate from a dict
name = x.get_name() # you didn't call the function at all
phone = x.get_phone() # members[x] not necessary
jersey = x.get_jersey()
outFile.write(name+", "+phone+", "+jersey+"\n") #missing + sign
print("Data Saved")
Working example
__init__.py
class Member:
def __init__(self, name, phone, jersey):
self.name = name
self.phone = phone
self.jersey = jersey
def get_name(self):
return self.name
def get_phone(self):
return self.phone
def get_jersey(self):
return self.jersey
def saveData(members):
filename = input("Filename to save: ")
with open(filename, 'wt') as outFile:
for x in members:
name = x.get_name()
phone = x.get_phone()
jersey = x.get_jersey()
outFile.write(name+", "+phone+", "+jersey+"\n")
print("Data Saved")
IDLE shell
>>> members = [Member("Dave", "123456789", "red"),
Member("Tom", "133742097", "yellow"),
Member("Elisa", "122333444", "blue"),
Member("John", "987654321", "blue")
]
>>> saveData(members)
Filename to save: output.txt
Data Saved
output.txt
Dave, 123456789, red
Tom, 133742097, yellow
Elisa, 122333444, blue
John, 987654321, blue
You can define getname, getphone in your Member class as follows:
class Member:
def getname(self):
return self.name
def getphone(self):
return self.phone
def getjersey(self):
return self.jersey
Then you can get values from getters in your saveData function :
name=members[x].getname()
phone=members[x].getphone()
jersey=members[x].getjersey()