We were asked to do the following:
Create a class Student with public member variables: Student name, student number, contact number, ID number. The following specifications are required:
Add init() method of the class that initializes string member variables to empty strings and numeric values to 0.
Add the method populate() to the class. The method is used to assign values to the member variables of the class.
Add the method display() to the class. The method is used to display the member variables of the class. (2)
Create an instance StudentObj of the class Student in a main program.
The main program should prompt the user to enter values for five students. The attributes should be assigned to the instance of Student using its populate() method, and must be displayed using the display() method of the instance of Student.
I have created an int function which initialises string variables to empty strings and numeric values to int variables, a populate function which assigns values to variables in the class and a display method to print the values of the class. The main method is supposed to ask the user to input their details and then print these details using the display() method.
class Student:
def __init__(self, student_name, student_num,contact_num,ID_num):
self.student_name = ""
self.student_num = 0
contact_num = 0
ID_num = 0
def populate(self,student_name, student_num,contact_num,ID_num):
self.student_name = student_name
self.student_num = student_num
contact_num = contact_num
ID_num = ID_num
def display(student_name, student_num,contact_num,ID_num):
print(student_name)
print(student_num)
print(contact_num)
print(ID_num)
def main():
StudentObj = Student()
s_name = int(input("Enter student name: "))
s_num = int(input("Enter student number: "))
con_num = int(input("Enter contact number: "))
ID_num = int(input("Enter ID number: "))
populate(s_name,s_num,con_num,ID_num)
display(s_name,s_num,con_num,ID_num)
if __name__ == '__main__':
main()
The program finished with exit code 0, however it does not ask for any inputs or print anything
As #Xteven suggested, call to the main function is missing.
You need
if __name__ == '__main__':
main()
Related
Taking a class on Python coding and trying to use inheritance to code an answer to this problem: Write an Employee class that keeps data attributes for the following piece of information:
Employee name
Employee ID
Employee phone #
Next, write a class named ProductionWorker class should keep data attributes for the following information:
Shift number (an integer, such as 1, 2, 3)
Room (bakery, topping, Quality control)
Hourly pay rate
The workday is divided into two shifts: day and night. The shift attribute will hold an integer value representing the shift that the employee works. The day shift 1 and the night shift is shift 2. Write the appropriate accessors and mutator methods for each class.
Once you have written the classes, write a program that creates an object of the ProductionWorker class which prompts the user to enter data for each of the object's data attributes. Store the data in the object, then use the object's accessor methods to retrieve it and display it to the screen.
Why am I getting the error I described in the title?
My Code:
class Employee(object):#Creates Superclass Employee
def __init__(self,name,EmplId,EmpPhone):#Creates Employee class with several parameters
self.name = name#Initial Attribute for Employee Name
self.EmplId = EmplId#Initial Attribute for Employee ID #
self.EmpPhone = EmpPhone#Initial attribute for Employee Phone #
class Worker(Employee):#Creates Subclass of Employee called Worker
def __init__(self,name,EmplId,ShiftNum,EmpPhone,PayRate):#Set initial state of Worker Subclass
Employee.__init__(self,name,EmplId,EmpPhone)
self.ShiftNum = ShiftNum#Initial Shift number value for class Worker
self.PayRate = PayRate#Initial Payrate for class Worker
def main():#Creates Main method
WorkerName = " "
WorkerIDNum = " "
WorkerShiftNum = 0
WorkerPayRate = 0.0
WorkerPhoneNum = " "
#Getting data attributes to passed into Employee and Worker classes
WorkerName = input("Enter the Workers name: ")
WorkerIDNum = ("Enter the Workers Id Number: ")
WorkerShiftNum = input ("Enter the Workers shift number (1,2,or 3): ")
WorkerPayRate = input ("Enter the works payrate in dollars an cents: ")
WorkerPhoneNum = input ("Enter the employees 9 Digit phone number:")
worker = Employee.Worker(WorkerName,WorkerIDNum,WorkerShiftNum,WorkerPhoneNum,WorkerPayRate)
#Above line creates an Instance of the Employee superclass and Worker subclass called "worker"
#Values the user entered are pass in as attributes to the object.
#Printing User entered information
print("Worker information entered: ")
print("Name: ", worker.name)
print("EMployee ID Number: ", worker.EmplId)
print("Employee Shift Number: ", worker.ShiftNum)
print("Worker Hourly Payrate: $", worker.PayRate)
main()```
The solution to your problem was provided in the comments... you must instantiate only the subclass (ie. Worker, not Employee.Worker), but I see more problems. My example below illustrates one way to fix them. You are creating a lot of arbitrary values, and not performing any checks or limits on them. Everything comes from outside of your class and needs to be clumsily injected into the __init__ arguments. Then to print the Worker you gather all of the data externally and format it into print statements. Why not make your classes smart enough to handle all of this internally?
To put this another way. You are basically just grabbing a bunch of junk, throwing it in a class constructor and calling it a Worker. You should be able to just call Worker and it handles getting, formatting and limiting everything that it expects.
Below we store all the final values in private variables. We tie all assignments to "setters" and trigger those "setters" in __init__. This allows us to force variables to satisfy certain conditions before we accept them. It also allows us to change properties of the Worker (after instantiation) while following the exact same system.
#Creates Superclass Employee
class Employee(object):
#property
def name(self) -> str:
return self.__name
#name.setter
def name(self, name:str) -> None:
while not name:
name = input("Enter The Worker's Name: ")
self.__name = name
#property
def phone(self) -> str:
return self.__phone
#phone.setter
def phone(self, phone) -> None:
phone = f'{phone}'
#get and check phone
while not phone.isdigit() or len(phone) != 10:
phone = input("Enter The Worker's 10 digit Phone Number: ")
#store phone
self.__phone = phone
#property
def eid(self) -> int:
return self.__eid
#eid.setter
def eid(self, eid) -> None:
if not isinstance(eid, int):
eid = f'{eid}'
#get and check employee id
while not eid.isdigit():
eid = input("Enter The Worker's ID Number: ")
eid = int(eid)
#store id
self.__eid = eid
def __init__(self):
self.name, self.phone, self.eid = '', '', ''
#Creates Subclass of Employee called Worker
class Worker(Employee):
#property
def shift(self) -> int:
return self.__shift
#shift.setter
def shift(self, shift) -> None:
if not isinstance(shift, int) or (isinstance(shift, int) and shift not in (1, 2, 3)):
shift = f'{shift}'
#get and check shift number
while not shift.isdigit() or not shift in ('1', '2', '3'):
shift = input("Enter The Worker's Shift Number (1, 2, 3): ")
shift = int(shift)
#store shift
self.__shift = shift
#property
def rate(self) -> float:
return self.__rate
#rate.setter
def rate(self, rate) -> None:
if not isinstance(rate, (float, int)):
rate = f'{rate}'
#get and check pay rate
while True:
try:
float(rate)
break
except ValueError:
pass
rate = input("Enter The Worker's Pay Rate in Dollars and Cents: ")
rate = float(rate)
#store rate
self.__rate = rate
def __init__(self):
Employee.__init__(self)
self.shift, self.rate = '', ''
#for printing the worker props
def __str__(self):
return f'Worker Information:\n\tname: {self.name}\n\tid: {self.eid}\n\tphone: {self.phone}\n\tshift: {self.shift}\n\trate: {self.rate}'
#this is so much cleaner. Make a Worker and print the instance.
if __name__ == "__main__":
worker = Worker()
print(worker)
import datetime
Class student:
def __init__(self,name,age):
self.name=[]
self.age=[]
def creat_student(self,name,age):
num=2
for n in range(num):
i=input("enter name of student")
self.name.append(i)
x=int(input("enter age of student"))
self.age.append(x)
#I want to call up the create_student function to enter information about students, If you implement the program, It does not happen, How I run it?
I guess you are trying to create a python class that creates classes of students with specified members with their names and ages. so with this assumption, you can do it in this way:
suppose we are going to create a mathematics class. first of all, you can specify the number of the class member students! so in this way, you tell python I want to create a class named mathematics_class with 5 members(for example)!
class student:
def __init__(self , num_students):
self.name=[]
self.age=[]
self.num = num_students
mathematics_class = student(5)
till now, we created a mathematics_class that has 5 students. but who are these students? here we go:
class student:
def __init__(self , num_students):
self.name=[]
self.age=[]
self.num = num_students
def creat_student(self):
"""
self refers to mathematics_class! in general, self refers to the instance of class!
"""
for n in range(self.num):
i=input("enter name of student")
self.name.append(i)
x=int(input("enter age of student"))
self.age.append(x)
mathematics_class = student(5)
# then you can call up the creat_student() to enter the information about students!
mathematics_class.creat_student()
when you run this code, python starts asking you to enter the name and age of each student one by one as you wish. but it would be great to add a function to print the name and age of each student of mathematics_class! here we go:
class student:
def __init__(self , num_students):
self.name=[]
self.age=[]
self.num = num_students
def creat_student(self):
"""
self refers to mathematics_class! in general, self refers to the instance of class!
"""
for n in range(self.num):
i=input("enter name of student")
self.name.append(i)
x=int(input("enter age of student"))
self.age.append(x)
def show_class_students(self):
print(dict(zip(self.name , self.age)))
mathematics_class = student(5)
# then you can call up the creat_student() to enter the information about students!
mathematics_class.creat_student()
# and use show_class_students() to print the mathematics_class members
mathematics_class.show_class_students()
for example if you try to enter name and age of each student like this:
amour 25
shayan 25
helen 26
anton 27
carol 23
then output would be:
{'amour': 25, 'shayan': 25, 'helen': 26, 'anton': 27, 'carol': 23}
I have created a class that takes name,id number and salary for each object. inside the class there are functions for adding or deduction of the salary and showing the status for each employee:
class emp():
def __init__(self,name,id_num,salary):
self.name=name
self.id=id_num
self.s=salary
def bounus(self,bon):
self.s+=bon
print(" the empolyee %s got a raise of %s"%(self.name,bon))
def ded(self,d):
self.s-=d
print(" the empolyee %s got a deduction of %s"%(self.name,d))
def show(self):
s="the employee {} with id number {} has a salary of {}".format(self.name,self.id,self.s)
print(s)
so I wanted to create a number of objects of my chioce using "range" function in the "for" loop as the following:
for i in range(1,3) :
o=str(input("Enter the employees number %s name\n"%i))
p=input("Enter his\her id number\n")
q=input("Enter his\her salary\n")
ai=emp(o,p,q)
ai.show()
in that way, it loops through 1 and 2 creating objects a1 and a2 and it worked but when I try to show them outside the loop as the following:
a1.show()
it says,a1 is undefined although I could show them inside the loop , how can I store the objects so I can show or apply functions on them after looping .thanks
The i in ai does not get processed as a seperated variable, it just becomes one whole ai.
Instead, you should make a list a, which you can access with a[i].
a = []
for i in range(2) : # Slight change to start at i=0
o=str(input("Enter the employees number %s name\n"%i))
p=input("Enter his\her id number\n")
q=input("Enter his\her salary\n")
a.append(emp(o,p,q))
a[i].show()
Selcuk identified your issue, but here is a code snippet based on your code that may help you conceptualize his advice:
new_employees = []
for i in range(1,3):
name = input("Enter the employees number %s name\n" %i)
id_num = input("Enter his\her id number\n")
salary = input("Enter his\her salary\n")
employee = emp(name, id_num, salary)
employee.show()
new_employees.append(employee)
At the end of the loop you will now have a list of new employees that you can do other things with. So, per your comment assume you want to deduct $25 from the salary of on the employee with the employee id of 5. You could something like this if you didn't want to get fancy:
target_employee = None
for employee in new_employees:
if employee.id == 5:
target_employee = employee
break
if target_employee:
target_employee.ded(25)
Here is another way that auto-creates a name for each employee the way you intended and stores that name and the employee object in a dictionary. Each employee can then be called by his name from outside the loop with full access to all the class methods. Also class names should always be capitalized. Object names are in lower case:
class Emp():
def __init__(self, name, id_num, salary):
self.name = name
self.id = id_num
self.s = salary
def bonus(self, bon):
self.s += bon
print("The empolyee %s got a raise of %s" % (self.name, bon))
def ded(self, d):
self.s -= d
print("The empolyee %s got a deduction of %s" % (self.name, d))
def show(self):
s = "The employee {} with id number {} has a salary of {}".format(self.name, self.id, self.s)
print(s)
employees = {}
for i in range(1, 3):
o = input("Enter the employees number %s name\n" % i)
p = input("Enter his\her id number\n")
q = int(input("Enter his\her salary\n"))
emp = Emp(o, p, q)
name = "a" + str(i)
employees[name] = emp
employees["a1"].show()
employees["a2"].bonus(500)
employees["a2"].ded(200)
employees["a2"].show()
The first mistake you have done is declaring the class inside the for loop. The scope of the object is limited to the for loop and will be destroyed after the loop and moreover you cannot store all the values wrt to the loop as every time a loop is run the new object will be invoked destroying all the previous one hence us the list to append them and try
Suppose I had this class
class employee(object)
def __init__(self,name):
return self.name
def something(self):
pass
...
Leading to
if __name__== "__main__":
name = input("what is your name ")
user1 = employee(name)
user1.something()
...
I want the user1 instance to be the name inputted by the user so that I can have unique instances. How do I go about adding instances based on user input in the main section?
so if I run the program and inputted "tim", the outcome I would want is:
tim.name = "tim"
....
UPDATE
Seems like the above is unclear, let me try to explain using my actual code:
So I have this Spotify API:
class Spotify(object):
def __init__(self,user):
self.client_id = ''
self.client_secret = ''
def client_credentials(self):
pass
def get_header_token(self):
pass
...
In the end,
if __name__== "__main__":
user = input("Enter username ")
user = Spotify(user)
user.request_author()
...
I am trying to get the user variable to the input the user provides, such as if the user inputted "tim123", the user variable would also be tim123.
So I could perform:
tim123.name
Think my mind is going completely blank and there should be an easy solution for this. I am sure this is very unpractical but I don't know how I would do this in case I ever needed to.
Change
return self.name
to
self.name = name
if name== "main":
variable_name = raw_input("Enter variable name:") # User.
enters "tim123"
name = input("Enter Name")
globals()[variable_name] = employee(name)
tim123.name
Based on your comment, it sounds like you are looking for exec() or eval(). Link. My solution would be to do something like:
class employee(object):
def __init__(self,name):
self.name = name
name = input("what is your name ")
exec(f"{name} = employee('{name}')")
(and then you would access joe.name, if the user inputted joe, or bob.name, if the user inputted bob, etc.).
Alternatively, you could use locals() or globals()
Hope this helped!
Here is my code as follows.
# starting of Employee class
class Employee(object):
def __init__(self): #declaring Constructor
self.name = ""
self.iDnumber = ""
self.department = ""
self.jobTitle = ""
# setter methode for setting values to the class properties
def setName(self,name):
self.name=name
def setIDnumber(self,iDnumber):
self.iDnumber=iDnumber
def setDepartment(self,department):
self.department=department
def setJobTitle(self,jobTitle):
self.jobTitle=jobTitle
# getter methode for getting values of the class properties
def getName(self):
return self.name
def getIDnumber(self):
return self.iDnumber
def getDepartment(self):
return self.department
def getJobTitle(self):
return self.jobTitle
# methode which takes object as an argument and display its properties
def display(emp_object):
print("Name : ",emp_object.getName())
print("IDnumber : ",emp_object.getIDnumber())
print("Department : ",emp_object.getDepartment())
print("JobTitle : ",emp_object.getJobTitle())
# Main methode of the program
if __name__ == "__main__":
employeeList = [] #List to hold the Employee objects
emp1 = Employee()
emp2 = Employee()
emp3 = Employee()
# appending objects to the list
employeeList.append(emp1)
employeeList.append(emp2)
employeeList.append(emp3)
# Initializing each objects of the list
for employee in employeeList:
emp_name = input("Enter your Name ")
employee.setName(emp_name)
emp_iDnumber = input("Enter your iDnumber ")
employee.setIDnumber(emp_iDnumber)
emp_department = input("Enter your Department ")
employee.setDepartment(emp_department)
emp_jobTitle = input("Enter your JobTitle ")
employee.setJobTitle(emp_jobTitle)
# Displaying each objects of the list
for emp_object in employeeList:
display(emp_object)
and, when I run it termianl just flash for a 10th of seconds and do not ask for input.
Help me with this thank you.
I am trying to focus on
Display a message asking user to enter employee name, ID, department, and title
b. Read employee name into a variable
c. Call the set name method of the first object passing the name
d. Read employee ID into a variable
Probably you are running it on windows... Simple add a input() at the end of you main to pause program and prevent windows from close it
And you need to indent your code
if __name__ == "__main__":
employeeList = [] #List to hold the Employee objects
emp1 = Employee()
emp2 = Employee()
emp3 = Employee()
# appending objects to the list
employeeList.append(emp1)
employeeList.append(emp2)
employeeList.append(emp3)
input()