Attribute Error for Python regarding an object - python

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()

Related

Program cannot Sort

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

Class object does not update empty list

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.

Python 3: vehicle inventory using class

I am having trouble getting my Python program to work for my class assignment. I have written what I think is the correct code but I still get errors like:
*NameError: name 'self' is not defined* Here is the Assignment:
Create a final program that meets the requirements outlined below.
Create an automobile class that will be used by a dealership as a vehicle inventory program. The following attributes should be present in your automobile class:
private string make
private string model
private string color
private int year
private int mileage
Your program should have appropriate methods such as:
constructor
add a new vehicle
remove a vehicle
update vehicle attributes
At the end of your program, it should allow the user to output all vehicle inventory to a text file.
Below is my code and any help is appreciated:
class Automobile:
def __init__(self, make, model, color, year, mileage):
self.make = make
self.model = model
self.color = color
self.year = year
self.mileage = mileage
def add_vehicle(self):
auto = Automobile()
vehicle_file = open('vehicle.txt', 'a')
make = input("Enter make: ")
model = input("Enter model: ")
color = input("Enter color: ")
year = input("Enter year: ")
mileage = input("Enter mileage: ")
vehicles = Automobile(make, model, color, year, mileage)
vehicle_list = [vehicles.make, vehicles.model, vehicles.color, vehicles.year, vehicles.mileage]
for i in vehicle_list:
vehicle_file.write("%s\t" % item)
vehicle_file.write("\n")
vehicle_file.close()
print("Your record has been succesfully added to the inventory")
def delete_vehicle(self):
del_rec = input("Enter record to delete: ")
with open("vehicle.txt","r+") as f:
new_f = f.readlines()
f.seek(0)
for line in new_f:
if del_rec not in line:
f.write(line)
f.truncate()
print("Succesfully deleted record from inventory")
def set_make(self, make):
self.make = make
def get_make(self):
return self.make
def set_model(self, model):
self.model = model
def get_model(self):
return self.model
def set_color(self, color):
self.color = color
def get_color(self):
return self.color
def set_year(self, year):
self.year = year
def get_year(self):
return self.year
def set_mileage(self, mileage):
self.mileage = mileage
def get_mileage(self):
return self.mileage
def main():
menu = {}
menu['1']="Add Vehicle."
menu['2']="Delete Vehicle."
menu['3']="Find Vehicle"
menu['4']="Exit"
user=True
while user:
print ("""
1.Add a Vehicle
2.Delete a Vehicle
3.View Inventory
4.Exit/Quit
""")
ans=input("What would you like to do? ")
if ans=="1":
Automobile.add_vehicle
elif ans=="2":
Automobile.delete_vehicle(self)
elif ans=="3":
print(Automobile.vehicles)
elif ans=="4":
print("\n Goodbye")
break
elif ans !="":
print("\n Invaild Entry")
if __name__ == "__main__":
main()
Assuming you are importing this module you have created and using it in main, it works fine for me. The only thing you need to change is to change i to item in your for loop, and remove the self in delete vehicle all the way at the bottom. This removed all of the errors for me from your class. Also Please do note that if you are supposed to be using private and protected variables you need to add for ex: __self.Make. Your variables are currently not private or protected. by adding the _ or __ modifier you make the variables private or protected. I'm guessing you have a vague idea of what private and protected do, but that's why you need the getter and setters. give that a shot and see if it helps! also if you are still unclear please make sure to look back over private and protected variables. also not sure if your add vehicle method will work at the bottom because you didn't close the parentheses. it should be addvehicle()

I'm trying to add objects to an array in python and then print the contents of the array [duplicate]

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

How to apply the amount of a raise given user's last 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)

Categories

Resources