I have only been programming for about a month and my question is this. Once I am done in the class defining the functions and class, how can I use the user input with the functions. Any help is appreciated the can shed a little light.
class employee:
def __init__(self,first,last,pay,hours):
self.first = raw_input("whats your first name")
self.last = raw_input("whats your last name")
self.pay = int(input("how much do you make an hour"))
self.hours = int(input("how many hours do you have"))
def raise_amount(self, amount):
self.pay = int(input('how much would you like to raise the employee pay'))
def overtime(self,overtime):
if self.hours !=39:
print ("there is an error you have overtime standby")
num1 = self.pay / 2
overtime = num1 + self.pay
print self.first, + self.overtime(self.hours)
print employee(self.hours)
As it stands this class does not make a lot of sense, particularly this bit:
class employee:
def __init__(self,first,last,pay,hours):
self.first = raw_input("whats your first name")
self.last = raw_input("whats your last name")
self.pay = int(input("how much do you make an hour"))
self.hours = int(input("how many hours do you have"))
By giving __init__ four arguments (in addition to self), it means that when you instantiate the class (via my_employee = employee(...)), you will have to pass all of those arguments, i.e. in your code you have to write my_employee = employee("John", "Cleese", "£2", "5 hours"). But that's pointless, because the __init__ function then completely ignores all of that information when it sets the attributes of the class, and instead uses user input. You just want to do this:
class employee:
def __init__(self):
self.first = raw_input("whats your first name")
self.last = raw_input("whats your last name")
self.pay = int(input("how much do you make an hour"))
self.hours = int(input("how many hours do you have"))
...
my_employee = employee()
It would be better however to create a general employee class, and then in circumstances where you need to create an employee via input, you can still do so. Specifically:
class Employee:
def __init__(self, first, last, pay, hours):
self.first = first
self.last = last
self.pay = pay
self.hours = hours
...
your_employee = Employee(input("First name: "), input("Last name: "),
int(input("Pay: ")), int(input("Hours: ")))
Related
Create an employee class with the following members: name, age, id, salary
setData() - should allow employee data to be set via user input
getData()- should output employee data to the console
create a list of 5 employees. You can create a list of objects in the following way, appending the objects to the lists.
emp_object = []
for i in range(5):
emp_ object.append(ClassName())
I'm trying to do this exercise and this is what I got:
class employee:
def __init__(self, n = None, a = None, i = None, s = None):
self.name = n
self.age = a
self.id = i
self.salary = s
def setData(self):
self.n = input("Enter name: ")
self.a = int(input("Enter age: "))
self.i = int(input("Enter id: "))
self.s = int(input("Enter salary: "))
self.getData()
def getData(self):
print("Name:", self.name, self.age, self.id, self.salary)
e1 = employee()
e1.setData()
e2 = employee()
e2.setData()
e3 = employee()
e3.setData()
e4 = employee()
e4.setData()
e5 = employee()
e5.setData()
emp_object = []
for i in range(5):
emp_object.append(employee())
print(emp_object)
It prints the employee details as "None" and I need help to create a list
Expected Output:
Name id Age Salary
AAA 20 1 2000
BBB 22 2 2500
CCC 20 3 1500
DDD 22 4 3500
EEE 22 5 4000
Change the instance variable self.n ( in the setData method) to self.name to match the declaration your class init method ...and do the same for the self.a, self.i... variables .
I beleive the problem is that you are not setting the parameters to the ones you want in the setData function.
You need to do this:
class employee:
def __init__(self, n = None, a = None, i = None, s = None):
self.name = n
self.age = a
self.id = i
self.salary = s
def setData(self):
self.name = input("Enter name: ")
self.age = int(input("Enter age: "))
self.id = int(input("Enter id: "))
self.salary = int(input("Enter salary: "))
self.getData()
def getData(self):
print("Name:", self.name, self.age, self.id, self.salary)
The __init__ and setData are two separate functions.
First you want to separate some responsabilities for a better reading.
We will divide the problem in two parts :
Employee model
Input/output problem
Employee
Create a class who contains only employee data (we can use dataclasses but, I assume you're a beginner, so I'll keep simple)
class Employee:
def __init__(self, uid=None, name=None, age=None, salary=None):
self.name = name
self.age = age
self.id = uid
self.salary = salary
Output and Input
To display the employee's data in console, we can use __str__ function. It is used when you class need to be converted into a str (in print for isntance).
We then add an other method in charge to set employee's data.
Our Employee class become :
class Employee:
def __init__(self, uid=None, name=None, age=None, salary=None):
self.name = name
self.age = age
self.id = uid
self.salary = salary
def __str__(self):
return f"Name: {self.name}, {self.age}, {self.id}, {self.salary}"
def set_data(self):
self.name = input("Enter name: ")
self.age = int(input("Enter age: "))
self.id = int(input("Enter id: "))
self.salary = int(input("Enter salary: "))
Our class is complete. Now we will write the algorithm in charge to create 5 employees.
So under the Employee class :
if __name__ == '__main__':
# Empty list containing our employees
employees = []
# We loop 5 times.
for i in range(5):
# We create an employee
employee = Employee()
# We set the data
employee.set_data()
# We append our brand-new employee into the list
employees.append(employee)
# Now we display our data :
for employee in employees:
# We just need to print the object thanks to __str__ method
print(employee)
Tell me if I answered correctly to your problem !
I was trying to add the parameter bonus (which will take an integer) with the instance variable self.pay and wanted to print that final payment with the worker's name. But, I could not print that added total payment
I want to call the method rise() instead of returning anything from it, but I am confused how I can call that and pass an integer number.
class Information:
def __init__(self,first,last,pay):
self.first = first
self.last = last
self.pay = pay
def rise(self,int(bonus)):
self.pay = self.pay + bonus
def __str__(self):
return "%s and %s and has a balance of %s" % (self.first,self.last,self.pay)
if __name__ == "__main__":
emp1 = Information("tom","jerry",999)
print (emp1)
class Information:
def __init__(self,first,last,pay):
self.first = first
self.last = last
self.pay = pay
def raise_salary(self, bonus):
self.pay += int(bonus) # exception if bonus cannot be casted
def __str__(self):
return "%s and %s and has a balance of %s" % (self.first,self.last,self.pay)
if __name__ == "__main__":
emp1 = Information("tom", "jerry", 999)
print(emp1)
emp1.raise_salary('1000') # or just emp1.raise(1000)
print(emp1)
I tried with below code.
I updated def rise(self,int(bonus)): to def rise(self,bonus):
class Information:
def __init__(self,first,last,pay):
self.first = first
self.last = last
self.pay = pay
def rise(self,bonus):
self.pay = self.pay + bonus
def __str__(self):
return "%s and %s and has a balance of %s" % (self.first,self.last,self.pay)
if __name__ == "__main__":
emp1 = Information("tom","jerry",999)
emp1.rise(89)
print (emp1)
Here's the simple python 3 object code from the web that is not platform dependent.. I cannot get working
class Employee:
def __init__(self, first, last, pay):
self.first = first
self.last = last
self.pay = pay
self.email = first + '.' + last + '#company.com'
def fullname(self):
return '{}{}'.format(self.first, self.last)
emp_1 = Employee('John','Doe','80000')
emp_2 = Employee('Jane','Foo','90000')
emp_2.fullname()
print (Employee.fullname(emp_1))
print (emp_2.fullname())
The error I get is as follows:
NameError Traceback (most recent call last)
in ()
----> 1 class Employee:
2
3 def init(self, first, last, pay):
4 self.first = first
5 self.last = last
in Employee()
10 return '{}{}'.format(self.first, self.last)
11
---> 12 emp_1 = Employee('John','Doe','80000')
13 emp_2 = Employee('Jane','Foo','90000')
14
NameError: name 'Employee' is not defined
Indentation is crucial in Python. Try the below code.
Your class instances must be defined outside the class itself. This is recognised by there being no indentation for definitions of emp_1 and emp_2.
class Employee:
def __init__(self, first, last, pay):
self.first = first
self.last = last
self.pay = pay
self.email = first + '.' + last + '#company.com'
def fullname(self):
return '{}{}'.format(self.first, self.last)
emp_1 = Employee('John','Doe','80000')
emp_2 = Employee('Jane','Foo','90000')
emp_2.fullname()
print(Employee.fullname(emp_1))
print(emp_2.fullname())
This is simply an indentation error.
Python defines scopes like classes, methods and other blocks by indentation. Usually 4 spaces are used.
Since you put your instantiation of emp_1 and emp_2 with the same indentation as the class's methods they are literally part of the class.
What you probably meant was:
class Employee:
def __init__(self, first, last, pay):
self.first = first
self.last = last
self.pay = pay
self.email = first + '.' + last + '#company.com'
def fullname(self):
return '{}{}'.format(self.first, self.last)
emp_1 = Employee('John','Doe','80000')
emp_2 = Employee('Jane','Foo','90000')
emp_2.fullname()
print (Employee.fullname(emp_1))
print (emp_2.fullname())
class Employee:
def __init__(self, first, last, pay):
self.first = first
self.last = last
self.pay = pay
self.email = first + '.' + last + '#company.com'
def fullname(self):
return '{}{}'.format(self.first, self.last)
def main():
emp_1 = Employee('John','Doe','80000')
emp_2 = Employee('Jane','Foo','90000')
emp_2.fullname()
print (Employee.fullname(emp_1))
print (emp_2.fullname())
if __name__ == '__main__':
main()
I have created employee details using class by giving pre defined inputs. I'm not able to store the results into a dict. I need to write it as a csv. I would be thankful if you could help me, as I'm a novice in python
Here are my codes:
Is it correct way to use for loop in classes?
class Employee():
def main(self,name,idno,position,salary):
self.name=name
self.idno=idno
self.position=position
self.salary = salary
def input(self):
n=int(raw_input("Enter the number of employees:"))
for i in range(n):
self.name=raw_input("Name:")
self.idno=raw_input("Idno:")
self.position=raw_input("position:")
self.salary=raw_input("salary:")
print("Name:", self.name, "Idno:", self.idno, "position:", self.position,
"salary:", self.salary)
if __name__=='__main__':
result=Employee()
result.input()
First of all, I don't think you're class will be working like you intend it to. Since you're constantly overwriting the class variables, there is no point in entering more than one employee, as the class can currently only save information on one employee. I would consider saveing employees as dictionarys and have those dictionaries saved as a list in your Employee(s) class.
class Employees():
all_employees = [{...}, {...}]
dict_keys = ["name", "idno", "position",...]
def input(self):
counter = 0
n = input("Number of employees: ")
while counter < n:
new_employee = dict()
for key in dict_keys:
new_employee[key] = raw_input("{}: ".format(key))
all_employees.append(new_employee)
if __name__ == "__main__":
e = Employees()
e.input()
This illustrates what I was saying in my comment about using a for loop outside of the class:
class Employee(object):
def __init__(self, name, idno, position, salary):
self.name=name
self.idno=idno
self.position=position
self.salary = salary
def print_data(self):
print("Name:", self.name, "Idno:", self.idno, "position:", self.position,
"salary:", self.salary)
if __name__=='__main__':
def input_employee_data():
print('Enter data for an employee')
name = raw_input("Name:")
idno = raw_input("Idno:")
position = raw_input("position:")
salary = raw_input("salary:")
print('')
return name, idno, position, salary
employees = list()
n = int(raw_input("Enter the number of employees:"))
for i in range(n):
name, idno, position, salary = input_employee_data()
employee = Employee(name, idno, position, salary)
employees.append(employee)
print('List of employess')
for employee in employees:
employee.print_data()
My goal with this program is to record 4 pieces of information (Employee Number, Employe Name, Shift Number, and Hourly Pay Rate) and then display them. I need to use classes in this program.
Here is the Class code:
class Employee(object):
def __init__(self, name, number):
self.__name = name
self.__number - number
def set_name(self, name):
self.__name = name
def set_number(self, number):
self.__number = number
def get_name(self):
return self.__name
def get_number(self):
return self.__number
class ProductionWorker(Employee):
def __init__(self, name, number,
shift, payRate):
Employee.__init__(self, name, number)
self.__shift = shift
self.__payRate = payRate
def set_shift(self, shift):
self.__shift = shift
def set_payRate(self, payRate):
self.__payRate = payRate
def get_shift(self):
return self.__shift
def get_payRate(self):
return self.__payRate
Here is the code that imports the class code and executes it:
import employee
name = input('Name: ')
number = input('Employee Number: ')
shift = input('Shift number (Enter 1 for day and 2 for night): ')
payRate = input('Hourly Pay Rate: ')
myEmployee = employee.ProductionWorker(name, number,
shift, payRate)
print('--------------------')
print('Employee Information')
print('--------------------')
print('Name:', myEmployee.get_name())
print('Employee Number:', myEmployee.get_number())
print('Customer number:', myEmployee.get_Shift())
print('Hourly Pay Rate:', myEmployee.get_payRate())
Okay, fixed type of:
myEmployee = employee.Employee(name, number,
shift, payRate)
to:
myEmployee = employee.ProductionWorker(name, number,
shift, payRate)
but now I am getting this error:
Traceback (most recent call last):
File "C:/Users/Alex/Desktop/Programming Concepts/Homework 2/Chapter 13/Employee and Production Worker Class.py", line 9, in <module>
shift, payRate)
File "C:/Users/Alex/Desktop/Programming Concepts/Homework 2/Chapter 13\employee.py", line 24, in __init__
Employee.__init__(self, name, number)
File "C:/Users/Alex/Desktop/Programming Concepts/Homework 2/Chapter 13\employee.py", line 5, in __init__
self.__number - number
AttributeError: 'ProductionWorker' object has no attribute '_Employee__number'
Thank you again for your help!
Change
myEmployee = employee.Employee(name, number,
shift, payRate)
to
myEmployee = employee.ProductionWorker(name, number,
shift, payRate)
Also, a piece of advice: writing getters and setters is generally frowned upon in Python. Just make the members public and get/set them like:
myEmployee.name = "David"
print myEmployee.name
Just change the following lines:
myEmployee = employee.Employee(name, number,
shift, payRate)
to
myEmployee = employee.ProductionWorker(name, number,
shift, payRate)
I guess that might be just a typo..
You mistook Employee with ProductionWorker in your main code.
Replace
myEmployee = employee.Employee(name, number,shift, payRate)
by
myEmployee = employee.ProductionWorker(name, number,shift, payRate)