Python Class Function not defined - python

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)

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 Composite Class JSON Serialization

I have what I would term a composite class
Whereby the class LegoSet is constructed from an instantiation of the class LegoSetVariant and inturn the class LegoSetVariant is constructed from a number of different class instantiations.
This is fine and I can successfully initialize the class. However, I then want to serialize the class object into JSON. This is proving a bit tricky as the composite classes are erroring as non-serializable.
class LegoSet:
def __init__(
self,
typename,
id,
productCode,
name,
slug,
primaryImage,
baseImgUrl,
overrideUrl,
variant,
):
self.__typename = typename
self.__id = id
self.__productCode = productCode
self.__name = name
self.__slug = slug
self.__primaryImage = primaryImage
self.__baseImgUrl = baseImgUrl
self.__overrideUrl = overrideUrl
self.__variant = variant
class LegoSetVariant:
def __init__(self, id, sku, salePercentage, attributes, price, listPrice):
self.__id = id
self.__sku = sku
self.__salePercentage = salePercentage
self.__atributes = attributes
self.__price = price
self.__listPrice = listPrice
class LegoSetVariantAttributes:
def __init__(
self,
rating,
maxOrderQuantity,
availabilityStatus,
availabilityText,
vipAvailabilityStatus,
vipAvailabilityText,
canAddToBag,
canAddToWishlist,
vipCanAddToBag,
onSale,
isNew,
featuredFlags,
):
self.__rating = rating
self.__maxOrderQuantity = maxOrderQuantity
self.__availabilityStatus = availabilityStatus
self.__availabilityText = availabilityText
self.__vipAvailabilityStatus = vipAvailabilityStatus
self.__vipAvailabilityText = vipAvailabilityText
self.__canAddToBag = canAddToBag
self.__canAddToWishlist = canAddToWishlist
self.__vipCanAddToBag = vipCanAddToBag
self.__onSale = onSale
self.__isNew = isNew
self.__featuredFlags = featuredFlags
class LegoSetVariantAttributesFeaturedFlags:
def __init__(self, key, label):
self.__key = key
self.__label = label
class LegoSetVariantPrice:
def __init__(self, formattedAmount, centAmount, currencyCode, formattedValue):
self.__formattedAmount = formattedAmount
self.__centAmount = centAmount
self.__currencyCode = currencyCode
self.__formattedValue = formattedValue
class LegoSetVariantListPrice:
def __init__(self, formattedAmount, centAmount):
self.__formattedAmount = formattedAmount
self.__centAmount = centAmount
Try this:
def unpack_into_dict(object):
res = {}
for key, val in object.__dict__.items():
if hasattr(val, '__dict__'):
res[key] = unpack_into_dict(val)
else:
res[key] = val
return res

I got some errors for implementation of GeneticAlgo

I am trying to make a time table scheduling program but found some errors. Please watch the following code and solve that error please.
Errors
These are the following errors
Traceback (most recent call last):
File "C:/Users/Muhammad Abbas/Downloads/ga02ClassScheduling.py", line 367, in <module>
population.get_schedules().sort(key=lambda x: x.get_fitness(), reverse=True)
File "C:/Users/Muhammad Abbas/Downloads/ga02ClassScheduling.py", line 367, in <lambda>
population.get_schedules().sort(key=lambda x: x.get_fitness(), reverse=True)
File "C:/Users/Muhammad Abbas/Downloads/ga02ClassScheduling.py", line 84, in get_fitness
self._fitness = self.calculate_fitness()
File "C:/Users/Muhammad Abbas/Downloads/ga02ClassScheduling.py", line 106, in calculate_fitness
if classes[i].get_room().get_seatingCapacity() < classes[i].get_course().get_maxNumbOfStudnets():
AttributeError: 'NoneType' object has no attribute 'get_seatingCapacity'
Source Code of the Program
Variables:
These are the variables which i declare for this program
import prettytable as prettytable
import random as rnd
POPULATION_SIZE = 9
NUMB_OF_ELITE_SCHEDULES = 1
TOURNAMENT_SELECTION_SIZE = 3
MUTATION_RATE = 0.1
Data Class
That is the first class which name is DATA
class Data:
ROOMS = [["R1", 25], ["R2", 45], ["R3", 35]]
MEETING_TIMES = [
["MT1", "MWF 09:00 - 10:00"],
["MT2", "MWF 10:00 - 11:00"],
["MT3", "TTH 09:00 - 10:30"],
["MT4", "TTH 10:30 - 12:00"]
]
INSTRUCTORS = [
["T1", "Dr James Web"],
["T2", "Mr Mike Brown"],
["T3", "Dr Steve Day"],
["T4", "Mrs Jane Doe"]
]
def __init__(self):
self._rooms = []
self._meetingTimes = []
self._instructors = []
for i in range(0, len(self.ROOMS)):
self._rooms.append(Room(self.ROOMS[i][0], self.ROOMS[i][1]))
for i in range(0, len(self.MEETING_TIMES)):
self._meetingTimes.append(MeetingTime(self.MEETING_TIMES[i][0], self.MEETING_TIMES[i][1]))
for i in range(0, len(self.INSTRUCTORS)):
self._instructors.append(Instructor(self.INSTRUCTORS[i][0], self.INSTRUCTORS[i][1]))
course1 = Course("C1", "325k", [self._instructors[0], self._instructors[1]], 25)
course2 = Course("C2", "319k", [self._instructors[0], self._instructors[1], self._instructors[2]], 35)
course3 = Course("C3", "462k", [self._instructors[0], self._instructors[1]], 25)
course4 = Course("C4", "464k", [self._instructors[2], self._instructors[3]], 30)
course5 = Course("C5", "360C", [self._instructors[3]], 35)
course6 = Course("C6", "303k", [self._instructors[0], self._instructors[2]], 45)
course7 = Course("C7", "303L", [self._instructors[1], self._instructors[3]], 45)
self._courses = [course1, course2, course3, course4, course5, course6, course7]
dept1 = Department("MATH", [course1, course3])
dept2 = Department("EE", [course2, course4, course5])
dept3 = Department("PHY", [course6, course7])
self._depts = [dept1, dept2, dept3]
self._numberOfClasses = 0
for i in range(0, len(self._depts)):
self._numberOfClasses += len(self._depts[i].get_courses())
def get_rooms(self):
return self._rooms
def get_instructors(self):
return self._instructors
def get_courses(self):
return self._courses
def get_depts(self):
return self._depts
def get_meetingTimes(self):
return self._meetingTimes
def get_numberOfClasses(self):
return self._numberOfClasses
Schedule Class
That is the second class which name is Schedule
class Schedule:
def __init__(self):
self._data = data
self._classes = []
self._numberOfConflicts = 0
self._fitness = -1
self._classNumb = 0
self._isFitnessChanged = True
def get_classes(self):
self._isFitnessChanged = True
return self._classes
def get_numberOfConflicts(self):
return self._numberOfConflicts
def get_fitness(self):
if(self._isFitnessChanged == True):
self._fitness = self.calculate_fitness()
self._isFitnessChanged = False
return self._fitness
def initialize(self):
depts = self._data.get_depts()
for i in range(0, len(depts)):
courses = depts[i].get_courses() #courses in each departments
for j in range(0, len(courses)):
newClass = Class(self._classNumb, depts[i], courses[j])
self._classNumb += 1
newClass.set_meetingTime(data.get_meetingTimes()[rnd.randrange(0, len(data.get_meetingTimes()))])
newClass.set_room(data.get_rooms()[rnd.randrange(0, len(data.get_rooms()))])
newClass.set_instructor(courses[j].get_instructors()[rnd.randrange(0, len(courses[j].get_instructors()))])
self._classes.append(newClass)
return self
def calculate_fitness(self):
self._numberOfConflicts = 0
classes = self.get_classes()
for i in range(0, len(classes)):
if classes[i].get_room().get_seatingCapacity() < classes[i].get_course().get_maxNumbOfStudnets():
self._numberOfConflicts += 1
for j in range(0, len(classes)):
if(j >= i):
if(classes[i].get_meetingTime() == classes[j].get_meetingTime() and
classes[i].get_id() != classes[j].get_id()):
if(classes[i].get_room() == classes[j].get_room()):
self._numberOfConflicts += 1
if(classes[i].get_instructor() == classes[j].get_instructor()):
self._numberOfConflicts += 1
return 1 / ((1.0*self._numberOfConflicts + 1))
def __str__(self):
# it returns all the classes of schedule separated by comas
returnValue = ""
for i in range(0, len(self._classes)):
returnValue += str(self._classes[i]) + ", "
returnValue += str(self._classes[len(self._classes)-1])
return returnValue
Population Class
Thats the third class which is Population class
class Population:
def __init__(self, size):
self._size = size
self._data = data
self._schedules = []
for i in range(0, size):
self._schedules.append(Schedule().initialize())
def get_schedules(self):
return self._schedules
GeneticAlgorithm Class
Thats the fourth class which is the GeneticAlgorithm class
class GeneticAlgorithm:
def evolve(self, population):
return self._mutate_population(self._crossover_population(population))
def _crossover_population(self, pop):
crossover_pop = Population(0)
for i in range(NUMB_OF_ELITE_SCHEDULES):
crossover_pop.get_schedules().append(pop.get_schedules()[i])
i = NUMB_OF_ELITE_SCHEDULES
while i < POPULATION_SIZE:
schedule1 = self._select_tournament_population(pop).get_schedules()[0]
schedule2 = self._select_tournament_population(pop).get_schedules()[0]
crossover_pop.get_schedules().append(self._crossover_schedule(schedule1, schedule2))
i += 1
return crossover_pop
def _mutate_population(self, population):
for i in range(NUMB_OF_ELITE_SCHEDULES, POPULATION_SIZE):
self._mutate_schedule(population.get_schedules()[i])
return population
def _crossover_schedule(self, schedule1, schedule2):
crossoverSchedule = Schedule().initialize()
for i in range(0, len(crossoverSchedule.get_classes())):
if (rnd.random() > 0.5):
crossoverSchedule.get_classes()[i] = schedule1.get_classes()[i]
else:
crossoverSchedule.get_classes()[i] = schedule2.get_classes()[i]
return crossoverSchedule
def _mutate_schedule(self,mutateSchedule):
schedule = Schedule().initialize()
for i in range(0, len(mutateSchedule.get_classes())):
if(MUTATION_RATE > rnd.random()):
mutateSchedule.get_classes()[i] = schedule.get_classes()[i]
return mutateSchedule
def _select_tournament_population(self, pop):
tournament_pop = Population(0)
i = 0
while i < TOURNAMENT_SELECTION_SIZE:
tournament_pop.get_schedules().append(pop.get_schedules()[rnd.randrange(0, POPULATION_SIZE)])
i += 1
tournament_pop.get_schedules().sort(key=lambda x:x.get_fitness(), reverse=True)
return tournament_pop
Course Class
Thats the fifth class which is the Course class
class Course:
def __init__(self, number, name, instructors, maxNumbOfStudents):
self._number = number
self._name = name
self._instructors = instructors
self._maxNumbOfStudents = maxNumbOfStudents
def get_name(self):
return self._name
def get_number(self):
return self._number
def get_instructors(self):
return self._instructors
def get_maxNumbOfStudents(self):
return self._maxNumbOfStudents
def __str__(self):
return self._name
Instructor Class
Thats the sixth class which is Instructor class
class Instructor:
def __init__(self, id, name):
self._id = id
self._name = name
def get_id(self):
return self._id
def get_name(self):
return self._name
def __str__(self):
return self._name
Room Class
Thats the seventh class which is the Room Class
class Room:
def __init__(self, number, seatingCapacity):
self._number = number
self._seatingCapacity = seatingCapacity
def get_number(self):
return self._number
def get_seatingCapacity(self):
return self._seatingCapacity
MeetingTime Class
Thats the eighth class which is MeetingTime class
class MeetingTime:
def __init__(self, id, time):
self._time = time
self._id = id
def get_id(self):
return self._id
def get_time(self):
return self._time
Department Class
Thats the ninth class which is the Department class
class Department:
# Batch for my case
def __init__(self, name, courses):
self._name = name
self._courses = courses # Courses that department offers
def get_name(self): return self._name
def get_courses(self): return self._courses
Class class
Thats is the tenth class which name is Class
class Class:
# Course to be scheduled at specific room of department host by an instructor at specific Meeting Time
def __init__(self, id, dept, course):
self._id = id
self._dept = dept
self._course = course
self._instructor = None
self._meetingTime = None
self._room = None
def get_id(self):
return self._id
def get_dept(self):
return self._dept
def get_room(self):
return self._room
def get_course(self):
return self._course
def get_instructor(self):
return self._instructor
def get_meetingTime(self):
return self._meetingTime
def set_instructor(self, instructor):
self._instructor = instructor
def set_meetingTime(self, meetingTime):
self._meetingTime = meetingTime
def set_room(self, room):
self_room = room
def __str__(self):
return str(self._dept.get_name()) + "," + str(self._course.get_number()) + "," + \
str(self._room.get_number()) + "," + str(self._instructor.get_id()) + "," + str(self._meetingTime.get_id())
DisplayMgr Class Plus End Code
Thats the eleventh class which is DisplayMgr Class and the end code of that program.
class DisplayMgr:
def print_available_data(self):
print("> All Available Data")
self.print_dept()
self.print_course()
self.print_room()
self.print_instructor()
self.print_meeting_times()
def print_dept(self):
depts = data.get_depts()
availableDeptsTable = prettytable.PrettyTable(['dept', 'courses'])
for i in range(0, len(depts)):
courses = depts.__getitem__(i).get_courses()
tempStr = "["
for j in range(0, len(courses) - 1):
tempStr += courses[j].__str__() + ", "
tempStr += courses[len(courses) - 1].__str__() + "]"
availableDeptsTable.add_row([depts.__getitem__(i).get_name(), tempStr])
print(availableDeptsTable)
def print_course(self):
availabelCoursesTable = prettytable.PrettyTable(['id', 'course # ', 'max # of students', 'instructors'])
courses = data.get_courses()
for i in range(0, len(courses)):
instructors = courses[i].get_instructors()
tempStr = ""
for j in range(0, len(instructors)-1):
tempStr += instructors[j].__str__() + ", "
tempStr += instructors[len(instructors) - 1].__str__()
availabelCoursesTable.add_row(
[courses[i].get_number(), courses[i].get_name(), str(courses[i].get_maxNumbOfStudents()), tempStr]
)
print(availabelCoursesTable)
def print_instructor(self):
availableInstructorsTable = prettytable.PrettyTable(['id', 'instructor'])
instructors = data.get_instructors()
for i in range(0, len(instructors)):
availableInstructorsTable.add_row([instructors[i].get_id(), instructors[i].get_name()])
print(availableInstructorsTable)
def print_room(self):
availableRoomsTable = prettytable.PrettyTable(['room #', 'max seating capacity'])
rooms = data.get_rooms()
for i in range(0, len(rooms)):
availableRoomsTable.add_row([str(rooms[i].get_number()), str(rooms[i].get_seatingCapacity())])
print(availableRoomsTable)
def print_meeting_times(self):
availableMeetingTimeTable = prettytable.PrettyTable(['id', 'Meeting Time'])
meetingTimes = data.get_meetingTimes()
for i in range(0, len(meetingTimes)):
availableMeetingTimeTable.add_row([meetingTimes[i].get_id(), meetingTimes[i].get_time()])
print(availableMeetingTimeTable)
def print_generation(self, population):
table1 = prettytable.PrettyTable(['schedule # ', 'fitness', '# of Conflicts','classes [dept, class, room, instructor'])
schedules = population.get_schedules()
for i in range(0, len(schedules)):
table1.add_row([str(i), round(schedules[i].get_fitness(),3), schedules[i].get_numberOfConflicts(), schedules[i]])
print(table1)
def print_schedule_as_table(self, schedule):
classes = schedule.get_classes()
table = prettytable.PrettyTable(['Class # ', 'Dept', 'Course (number, max # of students)', 'Room (Capacity', 'Instructor'])
for i in range(0, len(classes)):
table.add_row([str(i), classes[i].get_dept().get_name(), classes[i].get_course().get_name() + " (" +
classes[i].get_course().get_number() + ", " +
str(classes[i].get_course().get_maxNumbOfStudents()) + ")",
classes[i].get_room().get_number() + " (" + str(classes[i].get_room().get_seatingCapacity()) +
classes[i].get_instructor().get_name() + " (" + str(classes[i].get_instructor().get_id()) +")",
classes[i].get_meatingTime().get_time() + " (" + str(classes[i].get_meatingTime().get_id()) +")"
])
print(table)
data = Data()
displayMgr = DisplayMgr()
displayMgr.print_available_data()
generationNumber = 0
print("\n> Generation # " + str(generationNumber))
population = Population(POPULATION_SIZE)
population.get_schedules().sort(key=lambda x: x.get_fitness(), reverse=True)
displayMgr.print_generation(population)
displayMgr.print_schedule_as_table(population.get_schedules()[0]) # it will print fittest generation of schedule
geneticAlgorithm = GeneticAlgorithm()
while (population.get_schedules()[0].get_fitness() != 1.0):
generationNumber += 1
print("\n> Generation # " + str(generationNumber))
population = geneticAlgorithm.evolve(population)
population.get_schedules().sort(key=lambda x: x.get_fitness(), reverse=True)
displayMgr.print_generation(population)
displayMgr.print_schedule_as_table(population.get_schedules()[0])
print("\n\n")
def set_room(self, room):
self_room = room
you have missing . in set_room(self,room) function . Change it to self._room=room so that it will set the room value and objectType=None will be solved
Look into your the class DisplayMgr/def print_schedule_as_table
Change classes[i].get_meatingTime().get_time() to meetingTime

Printing sum of list items

What I need is to print the total a person has spent on products, I know the code is horrible but that's how I received the assignment. Never worked with Python so it's all a little mystery for me.
My result so far
The outcome should be 950 for Jeroen, 1175 for Martijn and 800 for Bart without printing them individually.
#start opdracht3 class
class opdracht3:
#start product class
class Product:
#constructor
def __init__(self, productname, price):
self.productname = productname
self.price = price
#end product class
#person class
class Person:
#constructor
def __init__(self, name, email, productlist):
self.name = name
self.email = email
self.productlist = productlist
#adding products to person's collection
def buyItem(self, item):
self.productlist.append(item)
#end person class
#collection of persons
persons = []
#defining person1 with the items he has bought
productlist1 = []
person1 = Person("Jeroen","jbm.mutsters#avans.nl", productlist1)
product1 = Product("Moto G7",150)
person1.buyItem(product1)
product3 = Product("iPhone",800)
person1.buyItem(product3)
#defining person2 with the items he has bought
productlist2 = []
person2 = Person("Martijn","m.dereus1#avans.nl", productlist2)
product2 = Product("iPhone",800)
person2.buyItem(product2)
product5 = Product("iPad",375)
person2.buyItem(product5)
#defining person2 with the items he has bought
productlist3 = []
person3 = Person("Bart","b.linsen#avans.nl", productlist3)
product4 = Product("iPhone",800)
person3.buyItem(product2)
#add person1 and person2 to the persons collection
persons.append(person1)
persons.append(person2)
persons.append(person3)
#generating output
for p in persons:
print(p.name)
for i in p.productlist:
print(i.productname)
print(i.price)
print("-----------------")
print("einde output")
print("***************")
#end generating output
#end opdracht3 class
Thanks in advance.
You can use the built-in sum to find the sum, and a list comprehension to get the prices from the items:
sum([x.price for x in p.productlist])
Same but in as a instance method:
class Person:
def __init__(self, name, email, productlist):
self.name = name
self.email = email
self.productlist = productlist
def buyItem(self, item):
self.productlist.append(item)
def get_sum_spend(self):
return sum([product.price for product in self.productlist])
Also, camel case methods naming typically is not used in Python. You can read more in pep8.
I added the method sum_product_prices to the person class which adds up the prices of the products in the persons productlist. Add the persons to the list persons and print out the return value of sum_product_prices. I removed the opdracht 3 class because it is not used.
#start product class
class Product:
#constructor
def __init__(self, productname, price):
self.productname = productname
self.price = price
#end product class
#person class
class Person:
#constructor
def __init__(self, name, email, productlist):
self.name = name
self.email = email
self.productlist = productlist
#adding products to person's collection
def buy_item(self, item):
self.productlist.append(item)
def sum_product_prices(self):
sum = 0
for product in self.productlist:
sum += product.price
return sum
#end person class
#collection of persons
persons = []
#defining person1 with the items he has bought
productlist1 = []
person1 = Person("Jeroen","jbm.mutsters#avans.nl", productlist1)
product1 = Product("Moto G7",150)
person1.buy_item(product1)
product3 = Product("iPhone",800)
person1.buy_item(product3)
persons.append(person1)
productlist2 = []
person2 = (Person("Martijn","x#y.com",productlist2))
person2.buy_item(product3)
product4 = Product("iPad",375)
person2.buy_item(product4)
persons.append(person2)
productlist3 = []
person3 = Person("Bart","a#b.com",productlist3)
person3.buy_item(product4)
persons.append(person3)
for person in persons:
print(person.name + " " + str(person.sum_product_prices()))

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