Creating a call function for multiple classes - python

So I got my code to work, but two lines are messing me up, and not quite sure what to put.
Code(the two lines are marked):
class Person(object):
numPerson = 0
def __init__(self,firstName,lastName):
self.firstName = firstName
self.lastName = lastName
def fullName(self):
print self.firstName +' '+self.lastName
class Employee(Person):
numEmployee = 0
def __init__(self,firstName,lastName,pay,employID):
Person.__init__(self, firstName, lastName)
self.pay = pay
self.employID = employID
Employee.numEmployee += 1
class Programmer(Employee):
def __init__(self,firstName,lastName,pay,employID,proLang):
self.proLang = proLang
Employee.__init__(self, firstName, lastName, pay, employID)
class Manager(Employee):
def __init__(self,firstName,lastName,pay,employID,progList):
self.progList = progList
Employee.__init__(self, firstName, lastName, pay, employID)
def addProgrammer(self):
self.progList.append(Programmer.fullName) <------------------- This line
def removeProgrammer(self):
if len(self.progList) == 0:
pass
else:
del self.progList[0]
def printList(self):
print self.progList
a = Manager('Alfred','Jones',20.00,0001,[])
b = Programmer('James','Smith', 11.75, 0002, 'Java')
a.addProgrammer() <--------------------------------------------- And This line
a.printList()
I'm trying to add the programmer's name to the progList using the .addProgramer method. I keep trying different combos and this is the closest I got.
Output:
[<unbound method Programmer.fullName>]
So, I'm not sure what needs to be in the addProgramer method in order to properly add the programmers name, or if I need an argument inside the a.addProgrammer at the very end.

Here:
self.progList.append(Programmer.fullName)
You're not adding an instance of a programmer, you are adding a method from the programmer class.
Also:
def fullName(self):
print self.firstName +' '+self.lastName
This doesn't actually return the name of the programmer, it only prints it to the console. To actually output and use the the fullname you need to return self.firstName + ' ' + self.lastName
Likewise in that function you also need to specify which programmer you are adding:
def addProgrammer(self, added_programmer):
self.progList.append(added_programmer.fullName()) # Call the function to get the fullname
And now to add a programmer:
Alfred = Manager('Alfred','Jones',20.00,0001,[]) #make a manager
James = Programmer('James','Smith', 11.75, 0002, 'Java') #make a programmer
Alfred.addProgrammer(James) #add the programmer
Alfred.printList()
Putting this all together:
class Person(object):
numPerson = 0
def __init__(self,firstName,lastName):
self.firstName = firstName
self.lastName = lastName
def fullName(self):
return self.firstName +' '+self.lastName
class Employee(Person):
numEmployee = 0
def __init__(self,firstName,lastName,pay,employID):
Person.__init__(self, firstName, lastName)
self.pay = pay
self.employID = employID
Employee.numEmployee += 1
class Programmer(Employee):
def __init__(self,firstName,lastName,pay,employID,proLang):
self.proLang = proLang
Employee.__init__(self, firstName, lastName, pay, employID)
class Manager(Employee):
def __init__(self,firstName,lastName,pay,employID,progList):
self.progList = progList
Employee.__init__(self, firstName, lastName, pay, employID)
def addProgrammer(self, added_programmer):
self.progList.append(added_programmer.fullName()) # Call the function to get the fullname
def removeProgrammer(self):
if len(self.progList) == 0:
pass
else:
del self.progList[0]
def printList(self):
print self.progList
Alfred = Manager('Alfred','Jones',20.00,1,[])
James = Programmer('James','Smith', 11.75, 2, 'Java')
Alfred.addProgrammer(James)
Alfred.printList()

Related

want to create random cards using faker

class BaseContacs:
def __init__(self, name, surname, phone, email):
self.name = name
self.surname = surname
self.phone = phone
self.email = email
#Variables
self._label_lenght = len(name) + len(surname) +1
def contact(self, ):
print(f" Wybieram numer", self.phone, "i dzwonię do", self.name, self.surname)
def __str__(self):
return f'{self.name} {self.surname} {self.phone} {self.email}'
#property
def label_lenght(self):
return self._label_lenght
class BuisnessContact(BaseContacs):
def __init__(self, position, company, company_phone, *args, **kwargs):
super().__init__(*args, **kwargs)
self.position = position
self.company = company
self.company_phone = company_phone
def buisnesscontact(self,):
print(f" Wybieram numer firmowy", self.company_phone, "i dzwonię do", self.name, self.surname, self.position, "w", self.company, "company")
kontakt1 = BaseContacs(name="Adam", surname="Nowak", phone=777666777, email="adam.nowak#op.pl")
kontakt2 = BuisnessContact(name="Stefan", surname="Jajko", phone=777667777, company_phone=727666777, email="stefan.jajko#op.pl",position="manager", company="diablo")
How can i add create_contacts function which can used faker to create random contacts?
I think it could be something like this:
def create_contacts(input):
but i don't know what's next

Python Class Function not defined

I'm creating a class with function within,
but i keep getting error "name 'direct_report' is not defined"
Basically im tring to make an organization chart, creating a list using the direct_report function to add people under each position
class employee:
def __init__(self, name , title, salary):
self.name = name
self.title = title
self.salary = salary
self.direct_reports_list = direct_report()
def __str__(self):
#otheremp_list = []
print(self.title,'-', self.name)
print('Direct Reports:')
for emp in self.direct_reports_list:
print(emp.title,'-', emp.name)
# otheremp_list.append(emp.direct_reports_list)
#print('other employees:')
#for emp in otheremp_list:
# print(emp.title,'-', emp.name)
# otheremp_list.append(emp.direct_reports_list)
def direct_report(self,value):
print(value)
direct_reports_list = []
direct_reports_list.append(value)
print(direct_reports_list)
return direct_reports_list
ceo = employee("Elon Musk", "CEO",1000000)
devdir = employee("Jeff Bezos","Development Director",500000)
devassoc1 = employee("Beyonce Knowles","Development Associate", 50000)
devassoc2 = employee("Taylor Swift","Development Associate", 50000)
ceo.direct_report(devdir)
ceo.direct_report(devdir2)
devdir.direct_report(devassoc1)
devdir.direct_report(devassoc2)
print(ceo)
The # is my further plan to print the full organization chart, but currently im still stuck at the "direct report" parts
You need to add one indentation level for the classes methods like that:
class employee:
def __init__(self, name , title, salary):
self.name = name
self.title = title
self.salary = salary
self.direct_reports_list = direct_report()
def __str__(self):
#otheremp_list = []
print(self.title,'-', self.name)
print('Direct Reports:')
for emp in self.direct_reports_list:
print(emp.title,'-', emp.name)
# otheremp_list.append(emp.direct_reports_list)
#print('other employees:')
#for emp in otheremp_list:
# print(emp.title,'-', emp.name)
# otheremp_list.append(emp.direct_reports_list)
def direct_report(self,value):
print(value)
direct_reports_list = []
direct_reports_list.append(value)
print(direct_reports_list)
return direct_reports_list
ceo = employee("Elon Musk", "CEO",1000000)
devdir = employee("Jeff Bezos","Development Director",500000)
devassoc1 = employee("Beyonce Knowles","Development Associate", 50000)
devassoc2 = employee("Taylor Swift","Development Associate", 50000)
ceo.direct_report(devdir)
ceo.direct_report(devdir2)
devdir.direct_report(devassoc1)
devdir.direct_report(devassoc2)
print(ceo)
Call the function in this way.
class employee:
def __init__(self, name , title, salary):
self.name = name
self.title = title
self.salary = salary
self.direct_reports_list = self.direct_report()
try self.direct_report() instead as you are calling a method within the class
Try this code.
class employee:
def __init__(self, name , title, salary):
self.name = name
self.title = title
self.salary = salary
self.direct_reports_list = []
def __str__(self):
#otheremp_list = []
print(self.title,'-', self.name)
print('Direct Reports:')
for emp in self.direct_reports_list:
print(emp.title,'-', emp.name)
# otheremp_list.append(emp.direct_reports_list)
#print('other employees:')
#for emp in otheremp_list:
# print(emp.title,'-', emp.name)
# otheremp_list.append(emp.direct_reports_list)
return "Done"
def direct_report(self,value):
self.direct_reports_list.append(value)
ceo = employee("Elon Musk", "CEO",1000000)
devdir = employee("Jeff Bezos","Development Director",500000)
devassoc1 = employee("Beyonce Knowles","Development Associate", 50000)
devassoc2 = employee("Taylor Swift","Development Associate", 50000)
ceo.direct_report(devdir)
devdir.direct_report(devassoc1)
devdir.direct_report(devassoc2)
print(ceo)
print(devdir)
print(devassoc1)
print(devassoc2)

How to access function output of one class from a function of another

I have two classes Course and Student. Course has a function that grades a student and gives a score. I'm trying to build a function in Student that takes that grade and shows the total score for a particular student.
class courseClass(object):
def grade(self, student, grade):
self.grade = grade
if self.grade == 1:
print("Student passed mandatory assignment")
elif self.grade == 0:
print("Student failed mandatory assignment")
elif self.grade != 0 or 1:
raise Exception("score is out of pattern range")
course_instance = courseClass()
course_instance.grade(student1, 1)
class Student(object):
def grade_status(self, student):
return [i.grade for i in self.grade]
student1 = Student("Bob Bobson", 20, 58008)
x = Student.grade_status(student1)
print(x)
AttributeError: 'Student' object has no attribute 'grade'
I think it needs to something like this instead:
def grade_status(self, grade):
self.grade =
But I don't know how to make it equal to the grade that's being given at the grade function (and will it know which student it is assigned to?)
Here is just one design (feel free to change the grading system):
class Course:
"""
Models a course being taught, for example: geometry
"""
def __init__(self, course_name):
self._course_name = course_name
self._enrollment = {} # No students so far
#property
def course_name(self):
"""Get the course_name."""
return self._course_name
def enroll_student(self, student):
"""
enroll student in this course
"""
self._enrollment[student] = None # no grade so far
student.add_course(self) # show that student is taking this course
return self
def enrollment(self):
"""
generate students enrolled in course
"""
for student, grade in self._enrollment.items():
yield student, grade
def assign_grade(self, student, grade):
"""
assign grade to a student
"""
assert student in self._enrollment
self._enrollment[student] = grade
return self
def get_grade(self, student):
"""
return a student's grade
"""
return self._enrollment[student]
class Student:
"""
Models a student
"""
def __init__(self, name):
self._name = name
self._courses = []
#property
def name(self):
"""Get student name"""
return self._name
def add_course(self, course):
self._courses.append(course)
return self
def courses(self):
for course in self._courses:
yield course
geometry = Course('geometry')
history = Course('history')
john_doe = Student('john doe')
jane_doe = Student('jane_doe')
geometry.enroll_student(john_doe)
geometry.enroll_student(jane_doe)
history.enroll_student(jane_doe)
geometry.assign_grade(john_doe, 1)
geometry.assign_grade(jane_doe, 2)
history.assign_grade(jane_doe, 1)
# print all the geometry grades
for student, grade in geometry.enrollment():
print(student.name, grade)
# print all of john_doe's courses and grades:
for course in john_doe.courses():
print('john_doe:', course.course_name, course.get_grade(john_doe))
for course in jane_doe.courses():
print('jane_doe:', course.course_name, course.get_grade(jane_doe))
Prints:
john doe 1
jane_doe 2
john_doe: geometry 1
jane_doe: geometry 2
jane_doe: history 1
I dont know if this what are trying to do
class courseClass(object):
def __init__(self, student, grade):
self.student = student
self.grade = grade
def grade_status(self):
if self.grade == 1:
return "Student passed mandatory assignment"
elif self.grade == 0:
return "Student failed mandatory assignment"
elif self.grade != 0 or 1:
raise Exception("score is out of pattern range")
class Student(object):
def __init__(self, name, age, random_number):
self.name = name
self.age = age
self.random_number = random_number
student1 = Student("Bob Bobson", 20, 58008)
course_instance = courseClass(student1,0)
x = course_instance.grade_status()
print(x)

How do I iterate through a list of objects

I'm trying to print a list(phonebook) of objects(record) but I'm new to python and it is not recognizing that record is a objects in the list. How would I call objects in this instance?
Ive tried looking at tutorials of python for loops but none reference how to call an object in a list.
class record:
def __init__(self,telephone,lastname,firstname):
self.telephone = telephone
self.lastname = lastname
self.firstname = firstname
class PhoneBook:
def __init__(self):
self.phonebook = []
def printphonebook(self):
for record in self.phonebook:
x = 0
print(self.phonebook[x])
x = x + 1
Expected output would be the list of objects including the telephone number, last name, and first name.
You want to print an instance of a class. So you should provide the special __str__ method to tell python how the object should be printed. __str__() must return a string: here the docs.
class record:
def __init__(self,telephone,lastname,firstname):
self.telephone = telephone
self.lastname = lastname
self.firstname = firstname
def __str__(self):
#returning a string with the content, you can edit the string to fit your needs.
#here I am using formatted string literals, works with python >= 3.6
return f"Last name: {self.lastname}, First Name: {self.firstname}, Telephone: {self.telephone}"
class PhoneBook:
def __init__(self):
self.phonebook = []
def printphonebook(self):
for entry in self.phonebook:
print(entry)
What happens here is that when you call print(record) the __str__() method is used to provide a string representing the content of the instance.
So if you do:
book = PhoneBook()
book.phonebook.append(record(800, "Wayne", "Bruce"))
book.phonebook.append(record(1234, "Kent", "Clark"))
book.phonebook.append(record(499, "Prince", "Diana"))
book.printphonebook()
This will print:
Last name: Wayne, First Name: Bruce, Telephone: 800
Last name: Kent, First Name: Clark, Telephone: 1234
Last name: Prince, First Name: Diana, Telephone: 499
You have no elements in your self.phonebook. Of course it prints nothing.
Every iteration you create x=0 so you always will print the first item:
class record:
def __init__(self,telephone,lastname,firstname):
self.telephone = telephone
self.lastname = lastname
self.firstname = firstname
class PhoneBook:
def __init__(self):
self.phonebook = [1,2,3,4,5]
def printphonebook(self):
for record in self.phonebook:
x = 0
print(self.phonebook[x])
x = x + 1
a = PhoneBook()
a.printphonebook()
1
1
1
1
1
Your x index is really pointless, you can just print record:
class record:
def __init__(self,telephone,lastname,firstname):
self.telephone = telephone
self.lastname = lastname
self.firstname = firstname
class PhoneBook:
def __init__(self):
self.phonebook = [1,2,3,4,5]
def printphonebook(self):
for record in self.phonebook:
print(record)
a = PhoneBook()
a.printphonebook()
1
2
3
4
5
So: 1. Fill your self.phonebook with ANY elements 2. Print record, without indices.

AttributeError: 'str' object has no attribute 'name', however I'm calling a function within a class(?)

Here is the whole program. I'm not sure why but the error says this but I am using a seperate .py program to test all the functions within this class and I ran into this error that I can't seem to find a solution to.
File "C:\Python\PythonLab\PythonLab.py\classes.py", line 73, in
printEmployeeNames
Supervisor.printName(worker) File "C:\Python\PythonLab\PythonLab.py\classes.py", line 56, in printName
print(str(self.name) + "'" + str(self.department)) AttributeError: 'str' object has no attribute 'name'
class Employee:
def __init__(self, fullname, datestart, monthstart, yearstart):
self.fullname = fullname
self.datestart = datestart
self.monthstart = monthstart
self.yearstart = yearstart
def getService(self):
from datetime import date
current_date = date.today()
date1 = date(self.yearstart, self.monthstart, 1)
date_now = date(current_date.year, current_date.month, 1)
serviceTime = date_now - date1
day_format = serviceTime.days
years = int((day_format/365))
months = int(((day_format % 365)/30))
if day_format < 0:
return('Still In Service')
if day_format == 1:
return("Last Service Time was Yesterday")
if day_format < 365:
return("Last Service Time was " + str(months) + " months ago.")
if day_format > 365:
return('Last Service Time was ' + str(years) + "-" + str(months) + " ago.")
def printName(self):
print(self.fullname)
def setName(self, name):
self.fullname = name
class Supervisor(Employee):
def __init__(self, name, datestart, department):
Employee.__init__(self, name, int(datestart[0:2]), int(datestart[2:4]), int(datestart[5:8]))
self.employees = {}
self.contact_info = {}
self.department = department
self.name = Employee.__name__
def getName(self):
return self.fullname
def printName(self):
print(str(self.name) + "'" + str(self.department))
def setName(self, name, department):
self.name = name
self.department = department
def addEmployee(self, Employee):
self.employees[str(Supervisor.getName(self))] = Employee
def isManager(self):
if self.employees:
return True
else:
return False
def printEmployeeNames(self):
for worker in self.employees:
Supervisor.printName(worker)
def removeEmployee(self, employeename):
for worker in self.employees:
if employeename in self.employees:
del self.employees[employeename]
def getContactInfo(self):
return self.employees
def setContactInfo(self, phone, fax, email):
self.contact_info["phone"] = phone
self.contact_info["fax"] = fax
self.contact_info["email"] = email
def getPhone(self):
return self.contact_info["phone"]
def getFax(self):
return self.contact_info["fax"]
def getEmail(self):
return self.contact_info["email"]
self.employees is a dict. Iterating it means iterating its keys. Thus, in this code
for worker in self.employees:
Supervisor.printName(worker)
worker is a string. Change it to:
for worker in self.employees:
Supervisor.printName(self.employees[worker])
Or, even more to the point:
for name, worker in self.employees.items(): # iterates key-value pairs
Supervisor.printName(worker)

Categories