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
Related
Hey I'm trying to get better at python and decided to go through classes. I run the code and it worked up until it calls the object Employees. It gives me an Attribute error: type object 'Employees' has no attribute 'HourlyAssociate'. Can anyone help me out. I've looked all over for a fix and tried a few things but I hit a wall.
class Employees:
def __init__(self, name):
self.name = name
def setName(self, name):
self.name = name
def getName(self):
return self.name
class SalariedEmployee(Employees):
def __init__(self, name, rate, monthly):
rate.monthly = monthly
Employees.__init__(self, name)
def setMonthly(rate, monthly):
rate.monthly = monthly
def getMonthly(rate, monthly):
return rate.monthly
class HourlyEmployee(Employees):
def __init__(self, name, rate, hourly, time, hours):
rate.hourly= hourly
Employees.__init__(self, name)
def setHourly(rate, hourly):
rate.hourly = hourly
def getHourly(rate):
return rate.hourly
def setHours(time, hours):
time.hours = hours
def getHours(time, hours):
time.hours = hours
import Employee
#main function
def main():
associates=AssociateList()
print('All associates hired for the company: ')
display_associates(associates)
#function for user input, and storing in the objects created. Then store in the array
def AssociateList():
#an empty array for employee data
associate_list = []
# Input to get the number of employee's date the user will be entering in
numOfAssociates = int(input('How many workers hired today? '))
#loop for input for each employee
for num in range(numOfAssociates):
#input data
name = input('Enter the name of the worker: ')
answer = str(input('Enter if associate is hourly or salary: '))
if answer == ('hourly'):
hours = int(input('Enter the amount of hours: '))
hourly = float(input('Enter the hourly rate: '))
else:
monthlyRate = int(input('Enter the monthly rate: '))
print()
associates = Employees.HourlyAssociate(name, hours, hourly)
associates = Employees.SalaryAssociate(name, hours, monthlyRate)
associate_list.append(associate)
return associate_list
def display_associate(associate_list):
for associate in associate_list:
print('Name:', associate.get_name())
print('Hourly rate: $', associate.get_Hourlyrate())
print('Hours worked: ', associate.get_Hours())
print()
#calls the main function
main()
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.
Here I have created constructor and set values for employee. But I have to Create suitable methods for reading employee information. Here I have input the employee information from outside the class. So, how can I create method to scan employee information
class Employee():
empCount = 0
def __init__(self, name, salary, dep):
self.name = name
self.salary = salary
self.dep = dep
Employee.empCount += 1
def displayEmployee(self):
print ("Name : ", self.name, ", Salary: ", self.salary, ", depatment: ", self.dep)
name={}
salary={}
dep={}
emp={}
for i in range (1,3):
print("Enter Your Details for Employee %d" % (i))
name[i]=input("Enter Your Name for employee:")
salary[i]=float(input("Enter Your Salary for employee:"))
dep[i]=input("Enter Your department for employee:")
emp[i] = Employee(name[i], salary[i],dep[i])
print("____________________________________________________")
for i in range (1,3):
emp[i].displayEmployee()
print ("Total Employee %d" % Employee.empCount)
It's difficult to understand what this scan employee information method should do. You have the one already there.
You could try the following simplified code:
class Employee():
empCount = 0
def __init__(self, name, salary, dep):
self.name = name
self.salary = salary
self.dep = dep
Employee.empCount += 1
def displayEmployee(self):
print ("Name : ", self.name, ", Salary: ", self.salary, ", depatment: ", self.dep)
employees = []
for i in range (1,3):
print("Enter Your Details for Employee %d" % (i))
name = input("Enter Your Name for employee:")
salary = float(input("Enter Your Salary for employee:"))
dep = input("Enter Your department for employee:")
employees.append(Employee(name, salary,dep))
for employee in employees:
employee.displayEmployee()
This depends largely on how your employee data is stored. If you are reading employee information from a csv file in the same directory, you could use os to get current directory location and pandas' read_csv to import the data from the file location as follows:
import os
import pandas as pd
class Employee():
empCount = 0
def __init__(self, emp_name, filename='all_employees_file.csv'):
self.file_loc = os.getcwd()+filename
self.df = pd.read_csv(file_loc)
self.name = emp_name
self.salary = df['salary'][df['name']==self.name]
self.dep = df['dep'][df['name']==self.name]
Employee.empCount += 1
def displayEmployee(self):
print ("Name : ", self.name, ", Salary: ", self.salary, ", depatment: ", self.dep)
billy = Employee('Billy McFarland')
billy.name #returns employee name
billy.salary #returns employee salary
billy.dep #returns employee department
billy.displayEmployee # To print as per sample in question
Also, based on code snippet in question, I assume that your intention is to use the class for creating a single object for a single employee. If so, empCount will not be of much use as each employee will be called on as a new instance of the Employee() class object. I would recommend either placing empCount outside of the class altogether and iterate through each employee, adding to empCount and creating an instance of Employee() for each if you intend to call the class for each individual. If planning on doing something for all employees, I would recommend building a single class object for the whole file for all employees. From this you could have displayEmployee(self, name) return details for any employee by feeding in their name.
A slight change on your code only
# Generally you assign object by assigning it to class like object = class_name
# THen you invoke or call a method by object.function_inside_class ,,,
#for you x.displayEmployee
class Employee():
empCount = 0
def __init__(self, name, salary, dep):
self.name = name
self.salary = salary
self.dep = dep
Employee.empCount += 1
def displayEmployee(self):
print ("Name : ", self.name, ", Salary: ", self.salary, ",
depatment: ", self.dep)
name={}
salary={}
dep={}
emp={}
p=Employee #creating object or instances
for i in range (1,3):
print("Enter Your Details for Employee %d" % (i))
name[i]=input("Enter Your Name for employee:")
salary[i]=float(input("Enter Your Salary for employee:"))
dep[i]=input("Enter Your department for employee:")
emp[i] = Employee(name[i], salary[i],dep[i])
print("____________________________________________________")
for i in range (1,3):
p.displayEmployee(emp[i]) # invoking method call by
# p.class = method , where p is object
print ("Total Employee %d" % Employee.empCount)
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
This is a section of my code that inputs the user's information into the system in order to determine if they get a raise. Ideally I would use variables and search the information given, however for my class I have to have a class statement.
class User:
num_of_users=0
raise_amount = 1.04
def __init__(self, first, last, spend):
self.first=first
self.last=last
self.spend=spend
self.email=first + "." + last + "#company.com"
User.num_of_users += 1
def fullname(self):
return "{} {}".format(self.first, self.last)
def apply_raise(self):
self.spend= self.spend*self.raise_amount
first=input("Enter in your first name:")
last=input("Enter your last name:")
spend=int(input("Enter in your availbe spend amount. This must be a positive number:"))
# these are hypothetical users in my system
user1=User(first,last,spend)
user2=User("Ryan", "Weber", 1000)
user3=User("Grant", "Freeland", 3000)
user4=User("Vicki", "Lepper", 1000)
user5=User("Haley", "Lepper", 500)
if last=={"Lepper"}:
user1.apply_raise=1.2
else:
user1.applyraise=1.04
print(user1.applyraise)
I'm not sure exactly what you're asking, but the code below is based on what you have (modified to follow the PEP 8 - Style Guide for Python Code).
I think it does what you say you want to do.
One issue may be that that it will apply the raise to every user with the same last name, so you might want to also check the first name.
class User:
num_of_users = 0
raise_amount = 1.04
def __init__(self, first, last, spend):
self.first = first
self.last = last
self.spend = spend
self.email = '{}.{}#company.com'.format(self.first, self.last)
User.num_of_users += 1
def fullname(self):
return '{} {}'.format(self.first, self.last)
def apply_raise(self, raise_amount=None):
if raise_amount is None:
raise_amount = User.raise_amount # use default
self.spend = self.spend * self.raise_amount
# Hypothetical users in my system.
users = [
User('Ryan', 'Weber', 1000),
User('Grant', 'Freeland', 3000),
User('Vicki', 'Lepper', 1000),
User('Haley', 'Lepper', 500)
]
first = input('Enter in your first name:')
last = input('Enter your last name:')
spend = int(input('Enter in your available spend amount. This must be a positive number:'))
for user in users:
if user.last == last:
user.apply_raise(1.2)
print(user.spend)