creat a list of instances of a class - python

class Employee():
def __init__(self, name, salary=0):
self.name = name
self.salary = salary
def hire(self):
hired = input('is employee hired? enter yes or no')
if 'yes' in hired:
hiresalary = int(input('enter employee salary'))
self.salary = hiresalary
def fire(self):
fired = input('is employee fired? enter yes or no')
if 'yes' in fired:
employeelist.remove(self.name)
if 'no':
pass
def raise_salary(self):
input("do you want to raise {}'s salary, enter yes or no".format(self.name))
if 'yes':
raise_sum = int(input("by how much do you want to raise {} salary?".format(self.name)))
self.salary += raise_sum
if 'no':
pass
I want to know if there's a way that every instance of the class will be stored in a list so that if i call the fire method i can delete that instance from the list.

As people above said, you would ideally store a list of employees outside of your Employee class. You could then change your Employee.fire() method to accept the list of employees like so:
employees = []
class Employee():
def __init__(self, name, salary=0):
self.name = name
self.salary = salary
def hire(self):
hired = input('is employee hired? enter yes or no')
if 'yes' in hired:
hiresalary = int(input('enter employee salary'))
self.salary = hiresalary
def fire(self, employeelist):
fired = input('is employee fired? enter yes or no')
if 'yes' in fired:
employeelist.remove(self)
return employeelist
def raise_salary(self):
input("do you want to raise {}'s salary, enter yes or no".format(self.name))
if 'yes':
raise_sum = int(input("by how much do you want to raise {} salary?".format(self.name)))
self.salary += raise_sum
if 'no':
pass
bob = Employee('Bob', 50)
employees.append(bob)
sally = Employee('Sally', 75)
employees.append(sally)
employees = bob.fire(employees)

Related

Python: return variable from class

from database import usernames
class names():
def __init__(self, name):
self.name = name
def name_in_use(self):
if self.name in usernames:
print(f"Sorry {self.name} is already taken. Please come up with a different username.")
name = names(input("How should we call you? ").capitalize())
name.name_in_use()
else:
print(f"Welcome, {self.name}!")
def new_user():
user_answer = input("Are you a new user? [y/n] ")
if user_answer == "y":
name = names(input("How should we call you? ").capitalize())
name.name_in_use()
else:
old_user = input("What is your username? ").capitalize()
print(f"Welcome, {old_user}!")
return
new_user()
How do I extract local name variable from class if it goes into else under name_in_use()?
I tried so many different ways but once outside of function python doesn't see it.
If an instance of names is supposed to use a unique name, that is something that should be enforced either in __init__, or better yet, before you call __init__. Use a class method to verify the name first.
class Name:
used_names = {}
def __init__(self, name):
self.name = name
self.used_names.add(name)
#classmethod
def from_unique_name(cls):
while True:
name = input("How should we call you?")
if name not in used_names:
break
print(f"Sorry {name} is already taken. Please come up with a different username.")
return cls(name)
# Returns an instance of Name or None
def new_user():
user_answer = input("Are you a new user? [y/n] ")
if user_answer == "y":
return Name.from_unique_name()
else:
old_user = input("What is your username? ").capitalize()
if old_user in Name.used_names:
print(f"Welcome, {old_user}!")
return Name(old_user)
else:
print("No user by the name of {old_user}")
user = new_user()
A couple of points to keep in mind:
If multiple threads could be creating new users, you should use a lock to make sure only one thread can append to Name.used_names at a time, and that no other thread can read from it while another thread is updating it.
new_user could also be a class method.
I find few problems in your code.
name_in_use function is recursive with no breaking condition
Code is repeating in new_user functions as well as name_in_use function inside the class
Return statements are missing
Here is the code I propose (Not tested but should work fine)
from database import usernames
class names():
def __init__(self, name):
self.name = name
def name_in_use(self):
if self.name in usernames:
print(f"Sorry {self.name} is already taken. Please come up with a different username.")
return None
else:
return self.name
def new_user():
user_answer = input("Are you a new user? [y/n] ")
if user_answer == "y":
while True:
name = names(input("How should we call you? ").capitalize())
new_name = name.name_in_use()
if new_name:
print(f"Welcome, {new_name}!")
break
else:
user_answer1 = input("You want to try again? [y/n] ")
if user_answer1 == "n":
break
else:
old_user = input("What is your username? ").capitalize()
print(f"Welcome, {old_user}!")
return

UnboundLocalError after user inputs last piece of data

Finishing up a database project and I'm having issues w/ it all coming together. I keep getting the below error after the user inputs the final data request.
Traceback (most recent call last):
File "c:/Users/j/Documents/Ashford U/CPT 200/Python Code/CPT 200 - Wk 5 Final Project JC.py", line 72, in <module>
main()
File "c:/Users/j/Documents/Ashford U/CPT 200/Python Code/CPT 200 - Wk 5 Final Project JC.py", line 42, in main
if employee_found is None:
UnboundLocalError: local variable 'employee_found' referenced before assignment
The user is to be able to input the requested data and it loop to the main question of adding, viewing, querying, or editing. So far its not looping back and I'm not sure where I've gotten off the wrong track at. Any help is much appreciated as I still have to add in the ability to write this to a file. Code below.
class Employee:
def __init__(self, name, ssn, phone, email, salary):
self.name = name
self.ssn = ssn
self.phone = phone
self.email = email
self.salary = salary
def add():
name = input("Please enter the employee's name: ")
ssn = input("Please enter the employee's ssn: ")
phone = str(input("Please enter the employee's phone number xxx-xxx-xxxx: "))
email = input("Please enter the employee's email: ")
salary = str(input("Please enter the employee's salary: "))
return Employee(name, ssn, phone, email, salary)
def formatEmployee(employee, name, ssn, phone, email, salary):
print(f'---------------------------- {name} -----------------------------')
print(f'SSN: {ssn}')
print(f'Phone: {phone}')
print(f'Email: {email}')
print(f'Salary: {salary}')
print('------------------------------------------------------------------------')
def main():
employee_list = []
#Loop of questions to add, search, edit, ect.
while True:
user_input = input('Please enter a command (add, view, query, edit): ')
if user_input == 'add':
new_employee = add()
employee_list.append(new_employee)
print(f'There are now ({(len(employee_list))}) employees in the database.')
if user_input == 'view':
for employee in employee_list:
#prints(employee_list)
formatEmployee(employee)
if user_input == 'find':
ssn = input('Enter employee SSN:')
employee_found = find(ssn, employee_list)
if employee_found is None:
print('Employee not found')
else:
formatEmployee(employee_found)
if user_input == 'edit':
ssn = input('Enter SSN of employee to edit their info: ')
employee_found = find(ssn, employee_list)
edit_field = input('Please enter the employee information that you want to edit: ')
new_info = input(f'Please enter the new: {edit_field}')
print('edit complete!')
# Employee edit branches
def edit(info, newinfo, employee):
if info == 'name':
employee.name = newinfo
if info == 'ssn':
employee.ssn = newinfo
if info == 'phone':
employee.phone = newinfo
if info == 'email':
employee.email = newinfo
if info == 'salary':
employee.salary = newinfo
#Query by SSN of employee
def find(ssn, employee_list):
for employee in employee_list:
if ssn == employee.ssn:
return employee
return None
main()
The problem is in your indentation... your main function should look like this:
def main():
employee_list = []
#Loop of questions to add, search, edit, ect.
while True:
user_input = input('Please enter a command (add, view, query, edit): ')
if user_input == 'add':
new_employee = add()
employee_list.append(new_employee)
print(f'There are now ({(len(employee_list))}) employees in the database.')
if user_input == 'view':
for employee in employee_list:
#prints(employee_list)
formatEmployee(employee)
if user_input == 'find':
ssn = input('Enter employee SSN:')
employee_found = find(ssn, employee_list)
if employee_found is None:
print('Employee not found')
else:
formatEmployee(employee_found)
if user_input == 'edit':
ssn = input('Enter SSN of employee to edit their info: ')
employee_found = find(ssn, employee_list)
edit_field = input('Please enter the employee information that you want to edit: ')
new_info = input(f'Please enter the new: {edit_field}')
print('edit complete!')

Trying to call an object from a different file but the output is only displaying blanks

For a homework, I made an employee class file. Then I made a separate program that has a menu, from which a user can add, edit, display the content of the employee file. however, when i am trying to display, the only output coming is blank.
employee.py:
class Employee:
def __init__(self, name, emplpoyeeid, department, job_title):
self.__name = ""
self.__employeeid = ""
self.__department = ""
self.__job_title = ""
def set_name(self, name):
self.__name = name
def set_id(self, employeeid):
self.__employeeid = employeeid
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_employeeid(self):
return self.__employeeid
def get_department(self):
return self.__department
def get_job_title(self):
return self.__job_title
The actual program file:
import pickle
from Employee import Employee
try:
filename=open('Employee.dat','rb')
dictionary=pickle.load(filename)
except:
dictionary={}
while True:
print('\n1. Look up an employee in the dictionary')
print('2. Add a new employee in the dictionary')
print("3. Change an existing employee's name,department and job title in the dictionary")
print('4. Delete an employee from the dicionary')
print('5. Quit the program\n')
choice=input('\nEnter a choice: ')
if choice == '1':
while True:
employeeid=input('\nEnter the ID of the employee: ')
if employeeid in dictionary:
ob=dictionary[employeeid]
print('Employee Name: ',ob.get_name())
print('Employee ID: ',ob.get_employeeid())
print('Employee department: ',ob.get_department())
print('Employee job title: ',ob.get_job_title())
break
else:
print('\nEmployee not found \n')
break
elif choice== '2':
while True:
name=input('\nEnter the name of the employee: ')
employeeid=input('\nEnter the employee id: ')
dept=input('\nEnter the employee department: ')
title=input('\nEnter the employee job title: ')
ob=Employee(name,employeeid,dept,title)
dictionary[employeeid]=ob
print("employee has been added")
break
elif choice== '3':
while True:
employeeid=input('\nEnter the employee ID to change the details: ')
if employeeid in dictionary:
ob=dictionary[employeeid]
while True:
name=input('\nEnter the new name of the employee: ')
ob.set_name(name)
dept=input('\nEnter the new department of the employee: ')
ob.set_department(dept)
title=input('\nEnter the new job title of the employee: ')
ob.set_job_title(title)
break
else:
print('\nID not found \n')
elif choice == '4':
while True:
employeeid=input('\nEnter the ID of the employee to delete: ')
if employeeid in dictionary:
del dictionary[employeeid]
print('\nEmployee data removed \n ')
else:
print("Employee data not found")
elif choice == '5':
filename=open('Employee.dat','wb')
pickle.dump(dictionary,filename)
filename.close()
else:
print('\nPlease enter a valid choice ')
Look up an employee in the dictionary
Add a new employee in the dictionary
Change an existing employee's name,department and job title in the dictionary
Delete an employee from the dicionary
Quit the program
Enter a choice: 2
Enter the name of the employee: sam
Enter the employee id: 1
Enter the employee department: 2
Enter the employee job title: 3 employee has been added
Look up an employee in the dictionary
Add a new employee in the dictionary
Change an existing employee's name,department and job title in the dictionary
Delete an employee from the dicionary
Quit the program 4
Enter a choice: 1
Enter the ID of the employee: 1 Employee Name: Employee ID:
Employee department: Employee job title:
Look up an employee in the dictionary
Add a new employee in the dictionary
Change an existing employee's name,department and job title in the dictionary
Delete an employee from the dicionary
Quit the program
Enter a choice:
I expected the values that i put initially to be in the second output
but it is only displaying blanks
First: Your Employee import is incorrect. If your filename is employee.py, you should write:
from employee import Employee
because your program can't find the file named Employee.py.
Second: Try not to use while True. It can easily throw your program in the infinite loop. For example: If you will select the fourth choice - Delete an employee from the dicionary - you will never return to the main menu because you can't break your infinite loop.
Third: Your Employee.__init__ creates empty fields:
class Employee:
def __init__(self, name, emplpoyeeid, department, job_title):
self.__name = ""
self.__employeeid = ""
self.__department = ""
self.__job_title = ""
and you use no setters in the main module. Of course it will return empty strings for every field. Add setters to the main module or change employee.py to this:
class Employee:
def __init__(self, name, emplpoyeeid, department, job_title):
self.__name = name
self.__employeeid = emplpoyeeid
self.__department = department
self.__job_title = job_title

Python Modules, passing values to args

Im learning python and am currently trying to pass values from input to the args for a module I wrote but I have no idea how to start.
Can someone give me some advice?
This is the module im calling
#!/usr/bin/python
class Employee:
'Practice class'
empCount = 0
def __init__(self, salary):
self.salary = salary
Employee.empCount += 1
def displayCount(self):
print "Total Employees %d" % Employee.empCount
def displayEmployee(self):
print "Salary: ", self.salary
class Att(Employee):
'Defines attributes for Employees'
def __init__(self, Age, Name, Sex):
self.Age = Age
self.Name = Name
self.Sex = Sex
def display(self):
print "Name: ", self.Name + "\nAge: ", self.Age, "\nSex: ", self.Sex
This is the code im using to call and pass the values to the args in the above module
#!/usr/bin/python
import Employee
def Collection1():
while True:
Employee.Age = int(raw_input("How old are you? "))
if Employee.Age == str(Employee.Age):
print "You entered " + Employee.Age + " Please enter a number"
elif Employee.Age > 10:
break
elif Employee.Age > 100:
print "Please enter a sensible age"
else:
print "Please enter an age greater than 10"
return str(Employee.Age)
def Collection2():
Employee.Name = raw_input("What is your name? ")
return Employee.Name
def Collection3():
while True:
Employee.Sex = str(raw_input("Are you a man or a woman? "))
if Employee.Sex == "man":
Employee.Sex = "man"
return Employee.Sex
break
elif Employee.Sex == "woman":
Employee.Sex = "woman"
return Employee.Sex
break
else:
print "Please enter man or woman "
Attributes = Employee.Employee()
Collection1()
Collection2()
Collection3()
Attributes.displayEmployee()
Im guessing I need to take the input from the user and place it in the variables of the class. I tried that but im guessing im doing everything wrong??
Employee.Age = int(raw_input("How old are you? "))
There's no use to setting a variable in the module instead of using a local variable, and setting whatever you need to set outside the Collection1() function. Note that you are not setting the employee (object) atributes', but the module's - this is probably not what you want. Also, functions, by convention, should be named with initial lowercase.
Your inheritance model is a bit strange. Why are the employee attributes in a different (sub) class? Generally, the attributes go into the main class constructor. If you really want to use a separate class for the attributes, you shouldn't use a subclass at all in this case.
EDIT
Here's what I think you meant to do:
#!/usr/bin/python
class Employee:
def __init__(self, salary, age, name, sex):
self.salary = salary
self.age= age
self.name= name
self.sex= sex
#Employee.empCount += 1 #don't do this. you should count instances OUTSIDE
def __str__(self):
return "Employee<Name: {0}, Age: {1}, Sex: {2}, Salary: {3}>".format( self.name, self.age, self.sex, self.salary)
def getAge():
while True:
try:
s=raw_input("How old are you? ")
age = int(s)
if age > 100:
print "Please enter a sensible age"
elif age<=10:
print "Please enter an age greater than 10"
else:
return age
except ValueError:
print "You entered " + s + " Please enter a number"
def getName():
return raw_input("What is your name? ")
def getSex():
while True:
sex = str(raw_input("Are you a man or a woman? "))
if not sex in ("man", "woman"):
print "Please enter man or woman "
else:
return sex
age= getAge()
name= getName()
sex= getSex()
salary=100000
employee = Employee(salary, age, name, sex)
print employee
if you want the Employee in a different file (module), just put it there and from your main code run from Employee import Employee (the first is the module, the second is the class).

Python raw_input into dictionary declared in a class

I am incredibly new to Python and I really need to be able to work this out. I want to be asking the user via raw_input what the module and grade is and then putting this into the dictionary already defined in the Student class as grades. I've got no idea what to do! Thanks in advance!
students = [] # List containing all student objects (the database)
def printMenu():
print "------Main Menu------\n" "1. Add a student\n" "2. Print all students\n" "3. Remove a student\n" "---------------------\n"
class Student:
firstName = ""
lastName = ""
age = 0
studentID = ""
degree = ""
grades = {"Module Name":"","Grade":""}
def setFirstName(self, firstName):
self.firstName = firstName
def getFirstName(self):
return self.firstName
def setLastName(self, lastName):
self.lastName = lastName
def getLastName(self):
return self.lastName
def setDegree(self,degree):
self.degree = degree
def getDegree(self):
return self.degree
def setGrades(self, grades):
self.grades = grades
def getGrades(self):
return self.grades
def setStudentID(self, studentid):
self.studentid = studentid
def getStudentID(self):
return self.studentid
def setAge(self, age):
self.age = age
def getAge(self):
return self.age
def addStudent():
count = 0
firstName = raw_input("Please enter the student's first name: ")
lastName = raw_input("Please enter the student's last name: ")
degree = raw_input("Please enter the student's degree: ")
while count != -1:
student.grades = raw_input("Please enter the student's module name: ")
#student.grades["Grade"] = raw_input("Please enter the grade for %: " % grades)
studentid = raw_input("Please enter the student's ID: ")
age = raw_input("Please enter the student's age: ")
student = Student() # Create a new student object
student.setFirstName(firstName) # Set this student's first name
student.setLastName(lastName)
student.setDegree(degree)
student.setGrades(grades)
student.setStudentID(studentid)
student.setAge(age)
students.append(student) # Add this student to the database
A few things:
Move the initialization of your class attributes into an __init__ method:
Get rid of all the getters and setters as Jeffrey says.
Use a dict that has module names as keys and grades as values:
Some code snippets:
def __init__(self, firstName, lastName, age, studentID, degree):
self.firstName = firstName
self.lastName = lastName
...
self.grades = {}
and:
while True:
module_name = raw_input("Please enter the student's module name: ")
if not module_name:
break
grade = raw_input("Please enter the grade for %s: " % module_name)
student.grades[module_name] = grade

Categories