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()
Related
I am generating a class of persons and want to get information about a certain person by input. I would like to use the str funtction because I am trying to understand it better. My Idea goes as follows:
class Person:
__init__(self, f_name, l_name):
self.f_name = f_name
self.l_name = l_name
__str__(self):
return "The persons full name is:" + f_name + l_name
person1 = Person(Peter, Punk)
person2 = Person(Mia, Munch)
person = input("What persons full name would you like to know?")
print(person) #I am aware that this just fills in the string saved in person, but how do I connect it to the variable?
another idea was to do it as follows:
#class stays the same except:
__init__(self, f_name, l_name):
self.f_name = f_name
self.l_name = l_name
list.append(self)
#and then for the main:
list = []
person1 = Person(Peter, Punk)
person2 = Person(Mia, Munch)
person = input("What persons full name would you like to know?")
index = list(person)
print(list[index])
Thankful for any edvice since I am obviously new to Python :D
I think OP has some concept problems here which this answer may go some way to help with.
Start by building a robust class definition. Simple in this case as there are just 2 attributes. Note the use of setters, getters and str, repr and eq dunder overrides.
A small function that checks if a given Person can be found in a list of Persons and reports accordingly.
Create a list with 2 different Person instances
Create another Person that is known not to match anything already in the list.
Run check()
Modify the 'standalone' Person to make it equivalent to something previously constructed.
Run check()
class Person:
def __init__(self, forename, surname):
self._forename = forename
self._surname = surname
#property
def forename(self):
return self._forename
#forename.setter
def forename(self, forename):
self._forename = forename
#property
def surname(self):
return self._surname
#surname.setter
def surname(self, surname):
self._surname = surname
def __str__(self):
return f'{self.forename} {self.surname}'
def __repr__(self):
return f'{self.forename=} {self.surname=}'
def __eq__(self, other):
if isinstance(other, type(self)):
return self.forename == other.forename and self.surname == other.surname
return False
def check(list_, p):
if p in list_:
print(f'Found {p}')
else:
print(f'Could not find {p}')
plist = [Person('Pete', 'Piper'), Person('Joe', 'Jones')]
person = Person('Pete', 'Jones')
check(plist, person)
person.surname = 'Piper'
check(plist, person)
Output:
Could not find Pete Jones
Found Pete Piper
You probably want a mapping between a name and an object. This is what Python's dict dictionary structure is for:
people = {} # an empty dictionary
people[f'{person1.f_name} {person1.l_name}'] = person1
people[f'{person2.f_name} {person2.l_name}'] = person2
This is creating a string of the first and last name.
You can then lookup the Person object using the full name:
print(people['Peter Punk'])
You could do this with list comprehension like so (also allowing multiple people to have the same first name)
class Person:
__init__(self, f_name, l_name):
self.f_name = f_name
self.l_name = l_name
__str__(self):
return "The persons full name is:" + f_name + l_name
personList= []
personList.append(Person(Peter, Punk))
personList.append(Person(Mia, Munch))
personName = input("What persons full name would you like to know?")
print([str(person) for person in personList if person.f_name == personName])
#I need to figure out how to save the user input as the new variables, not sure what to do from here.
class Person:
def __init__(self):
#I'm supposed to have the object set to these generic names at first and then after the prompt function they need to be updated.
self.name = 'anonymous'
self.b_year = 'unknown'
def prompt(self):
print('Please enter the following:')
self.name = input('Name: ')
self.b_year = input('Year: ')
b = Book()
b.prompt()
def display(self):
print(f'Author:\n{self.name} (b. {self.b_year})\n')
class Book:
def __init__(self):
self.title = 'untitled'
self.publisher = 'unpublished'
def prompt(self):
self.title = input('Title: ')
self.publisher = input('Publisher: ')
def display(self):
print(f'\n{self.title}\nPublisher:\n{self.publisher}')
p = Person()
`enter code here`p.display()
def main():
p = Person()
b = Book()
b.display()
p.prompt()
b.display() #right here I need it to display the new information
if __name__ == '__main__':
main()
Two things you need to do here. First of all you need to initialize your variables in your Person class. Second of all I don't understand what the point of creating objects in a class and then doing the same outside of the class. I suggest taking the following code and modifying it to your likings. Additionally I reorganized the way you call your methods. First you prompt the user with all the necessary questions, then display them all together.
class Person:
def __init__(self):
self.name = None
self.b_year = None
def prompt(self):
print('Please enter the following:')
self.name = input('Name: ')
self.b_year = input('Year: ')
def display(self):
print(f'Author:\n{self.name} (b. {self.b_year})\n')
class Book:
def __init__(self):
self.title = 'untitled'
self.publisher = 'unpublished'
def prompt(self):
self.title = input('Title: ')
self.publisher = input('Publisher: ')
def display(self):
print(f'\n{self.title}\nPublisher:\n{self.publisher}')
def main():
p = Person()
b = Book()
b.display()
p.display()
p.prompt()
b.prompt()
b.display()
p.display()#right here I need it to display the new information
if __name__ == '__main__':
main()
output
untitled
Publisher:
unpublished
Author:
None (b. None)
Please enter the following:
Name: a
Year: b
Title: c
Publisher: d
c
Publisher:
d
Author:
a (b. b)
I'm not designer so you don't have to go with my idea, but IMO, don't add \n like this '\n{self.title}\nPublisher:\n{self.publisher}'. It looks a bit weird in the output.
You create one Book in the main function, and then another Book inside the Person.prompt method. They aren't the same Book - you have two!
You need to decide if a book belongs within a person, or whether they are two top level objects that may have a relationship. From a "real world" perspective, I don't think a person should automatically have a book associated with them. Perhaps you could create a Book and then pass to the Person constructor...
I have a niche problem. I create a class classA, with attributes name and number. Once a class item is created, its name is stored as a string in a list, namesList. Later in the code, namesList prints and the user can enter a string input. If that input matches a string in namesList, I want the program to print the number attribute associated with that class item. How should I do this?
ClassA is just a class. You tried to reference it in the last line which leads to an error. Instead of doing that appending the object to the list would be better because then you can individually get the value back from the object while searching in the array.
namesList = []
class classA:
def __init__(self, name, number):
self.name = name
self.number = number
namesList.append(self)
def getNumber(self):
return self.number
def getName(self):
return self.name
example = 'c'
classA(example, 5)
userChoice = input('Which name do you need the number for?')
for name in namesList:
if name.getName() == userChoice:
nameIndex = namesList.index(name)
print(nameIndex)
print('The current price for', name.getNumber())
I think what you're trying to do is this:
namesList = []
class classA:
def __init__(self, name, number):
self.name = name
self.number = number
namesList.append(self.name)
example_Class = classA('example', 5)
userChoice = input('Which name do you need the number for?')
for name in namesList:
if name == userChoice:
print('The number is', example_Class.number)
You have to set classA('example', 5) equal to a variable example_Class and then if you want to access the number value stored it's just example_Class.number
EDIT
This code ought to work regardless of how many class items there are:
class Iterator(type):
def __iter__(cls):
return iter(cls.namesList)
class ClassA(metaclass=Iterator):
namesList = []
def __init__(self, name, number):
self.name = name
self.number = number
self.namesList.append(self)
example_Class1 = ClassA('one', 8)
example_Class2 = ClassA('two', 7)
example_Class3 = ClassA('three', 6)
userChoice = input('Which name do you need the number for?')
for class_name in ClassA:
if class_name.name == userChoice:
print('The number is', class_name.number)
I have a simple program that takes user name and age using user input. How can I store the data on dictionary and update the data if another user put new name and age. Here is my sample code. I don't know if I'm doing it right.
class Name:
data = {}
num_employee = 0
def __init__(self, name, age):
self.name = name
self.age = age
Name.num_employee += 1
#classmethod
def user_in(cls):
name = input('Enter name: ')
age = int(input('Enter age: '))
return cls(name, age)
def show(self):
Name.data = {'name': self.name, 'age': self.age}
return Name.data
employ = Name.user_in()
employ2 = Name.user_in()
print(Name.num_employee)
print(employ.show())
Every instance of a Name class would be a person with name and age. Now i'm not getting if you're supposing an employee can have more than one name (and this is why you need a dictionary) or you simply need an object to collect information about every user.
If you want to mantain the input inside of the class move it to the constructor, that is __init__ method.
I would use another object such as a list to collect the set of users.
I also added two method to the class Person allowing user to modify age and name with a new input.
class Person:
def __init__(self):
self.name = input('Enter name: ')
self.age = int(input('Enter age: '))
def show(self):
data = {'name': self.name, 'age': self.age}
return data
def change_name(self):
self.name = input('Update name: ')
def change_age(self):
self.age = int(input('Update age: '))
persons = []
employ = Person()
employ2 = Person()
# add employ to the list
persons.append(employ)
persons.append(employ2)
# to show information
print(len(persons)) # len of the list is the number of employees
print(employ.show())
# to change employ1 name you can do
employ.change_name()
# to change employ2 age do
employ2.change_age()
I've never used classes before and I am trying to get a general understanding of how they work with the code example I have below. Im having issues referencing one of the names i define for a class. i just want the program to print out a list of the employee names and salaries stored in the list when the option 2 is entered but it gives me the following error:
Traceback (most recent call last):
File "C:\Scott Glenn\Misc\classes.py", line 31, in
employees[i].displayEmployee
AttributeError: 'str' object has no attribute 'displayEmployee'
class Employee:
'Common base class for all employees'
empCount = 0
def __init__(self, name, salary):
self.name = name
self.salary = salary
Employee.empCount += 1
def displayCount(self):
print "Total Employee %d" % Employee.empCount
def displayEmployee(self):
print "Name : ", self.name, ", Salary: ", self.salary
def AddNewEmployee():
NewEmployee = raw_input("What is the Employees name: ")
employees.append(str(NewEmployee))
NewEmployeeSalary = raw_input("What is the Employees salary: ")
NewEmployee = Employee(NewEmployee, NewEmployeeSalary)
return employees
#=============================================================================
employees=[]
while(1):
print'Welcome to the Employee Database!'
option = raw_input('Please select 1 to add new employee or 2 to display all current employees: ')
if option=='1':
employees.append(AddNewEmployee())
if option=='2':
for i in range(0,len(employees)):
employees[i].displayEmployee
The AddNewEmployee function is wrong. It's returning a list of a single string when you want to be returning a single object of your custom type Employee.
It should be more like this:
def AddNewEmployee():
#string variable to hold name
NewEmployeeName = raw_input("What is the Employees name: ")
#why make a list? you are appending the result of this function to that list
#employees.append(str(NewEmployee))
#plus this is adding the employee before he's even been created
NewEmployeeSalary = raw_input("What is the Employees salary: ")
#construct using name string and salary string
NewEmployee = Employee(NewEmployeeName, NewEmployeeSalary)
return NewEmployee #return Employee object (to be appended later)
Additionally, you are trying to access displayEmployee() as a field of your class, instead of as a method. Fields don't have parenthesis and methods do (so they can take parameters, though in this case the parenthesis are empty as no parameters are passed).
Finally, note that raw_input returns a string so you should cast to float if that is what you wish your NewEmployeeSalary to be. (Right now it's a string.)
I've updated your code below. The main issue that I saw that you had was that you were using 'employees' as a global and appending to it twice. I moved it out of the AddNewEmployee() function and had that return the new employee which is then appended to 'employees'
Also you weren't calling '.displayEmployees'
Notice the the parentheses that I added to the end.
I hope this helps!
class Employee(object):
'Common base class for all employees'
empCount = 0
def __init__(self, name, salary):
self.name = name
self.salary = salary
Employee.empCount += 1
def displayCount(self):
print "Total Employee %d" % Employee.empCount
def displayEmployee(self):
print "Name : ", self.name, ", Salary: ", self.salary
def AddNewEmployee():
NewEmployee = raw_input("What is the Employees name: ")
NewEmployeeSalary = raw_input("What is the Employees salary: ")
NewEmployee = Employee(NewEmployee, NewEmployeeSalary)
return NewEmployee
# =============================================================================
if __name__ == "__main__":
employees = []
while True:
print'Welcome to the Employee Database!'
option = raw_input(
'Please select 1 to add new employee or 2 to display all current employees: ')
if option == '1':
employees.append(AddNewEmployee())
if option == '2':
for i in range(0, len(employees)):
employees[i].displayEmployee()