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()))
Related
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)
I am trying to complete a series of class definition tasks and can't seem to get past this one. It is part of a 3 part series; the first part asks you to model a library book, which I could complete easily.
The next part is asking to create a Member class to model a library member and include a borrow_book() and a return_book() method, and to get the member's list of all loan books to print out in alphabetical order.
I cannot understand which part I am going wrong on. Could someone possibly point me in the right direction? I have included my code so far below.
class Book(object):
def __init__(self, title, author, copies=1, loan=0):
self.title = title
self.author = author
self.copies = copies
self.loan = loan
def checkbook(self, title):
for book in self.title:
if book.title in self.title:
return book
else:
print("Sorry, Not Available.")
def borrow_book(self):
abc = self.checkbook(title)
print(abc)
self.loan += 1
self.copies -= 1
def return_book(self):
self.loan -= 1
def __str__(self):
r = []
r.append('Title: {}'.format(self.title))
r.append('Author: {}'.format(self.author))
r.append('Copies: {}'.format(self.copies))
r.append('On loan: {}'.format(self.loan))
return '\n'.join(r)
def sort_books(b):
return b.title
class Member(object):
def __init__(self, mid, name, loans=0):
self.mid = mid
self.name = name
self.loans = loans
self.d = {}
def __str__(self, mid, name, loans=0):
r = []
r.append('ID: {}'.format(self.mid))
r.append('Name: {}'.format(self.name))
r.append('Loans: {}'.format(self.loans))
l = ['{}'.format(b) for b in sorted(self.d.values(), key=sort_books)]
return '\n'.join(r)
return '\n'.join(l)
I'm having a problem with my python program where I'm trying to create a class that holds data about an item in a retail store. I don't know why it's giving me NameError. Also, would it be possible to convert the data in storeProducts list into a dictionary and still have it displayed as a table
class Products:
def __init__(self,productId,description,quantity,price):
self.productId = productId
self.description = description
self.quantity = quantity
self.price = price
def set_productId(self,productId):
self.__productId = productId
def set_description(self,description):
self.__description = description
def set_quantity(self,quantity):
self.__quantity = quantity
def set_price(self,price):
self.__price = price
def get_productId(self,productId):
return self.__productId
def get_description(self,description):
return self.__description
def get_quantity(self,quantity):
return self.__quantity
def get_price(self,price):
return self.__price
def __str__(self):
return'Products:'+ 'title:' + self.title+', description:' + self.description + \
' ,quantity' + self.quantity + ', price:' + self.price
def main():
storeProducts = [[1,'Jacket',1,59.95],
[2, 'Designer Jeans' , 40, 34.95],
[3, 'Shirt' , 20, 24.95],]
print=(': Product ID : Description : Quantity : Price : ')
for item in storeProducts:
print(':',item[0],''*(9-len(str(item[0]))), ':',
item[1],''*(11-len(item[1])),':',
item[2],''*(8-len(str(item[2]))),':',
item[3],''*(5-len(str(item[3]))))
main()
If you copy-pasted the code properly, there's a clear indentation problem in your main function.
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.
Attempting to create a program in python 3 that takes object(s) created from one class item to another, shoppingCart. The idea is to create a list of objects created by the item class using the shoppingCartclass, while still being able to access attributes of the item class such as price and quantity.
class item:
def __init__(self,n,p,q):
self.name = n
self.price = p
self.quantity = q
def show(self):
z = (str(self.name))
print(z)
self1 =("$")+(str(self.price))
print(self1)
def getName(self):
return self.name
def getPrice(self):
return ("$") + str(self.price)
def getQuantity(self):
return self.quantity
class shoppingCart:
def __init__(self, items):
self.items = []
def show(self):
print(self.items)
def addItem(self,item):
if item not in self.items:
self.items.append(item)
else:
item.q += 1
def deleteItem(self,item):
if item in self.items:
self.items.remove(item)
else:
return print("Not in Cart")
def checkOut (self):
total = 0
for i in self.items:
price = i[1]
total += price
return total
item1 = item("Chocolate",5 ,3)
item2 = item("Bacon",15,1)
item3 = item("Eggs",2,5)
c = shoppingCart([])
c.addItem(item1)
c.addItem(item2)
c.addItem(item3)
c.show()
print ("You have 3 items in your cart for a total of" (c.checkOut()))
c.removeItem(item3)
print ("You have 2 items in your cart for a total of" (c.checkOut()))
The above code currently creates two errors, firstly, the c.show is printing the IDs of the objects appended to the shopping cart. In addition, the checkOut method creates an error regarding price = i[1] saying that the item object does not support indexing. Alternate solutions to this problem that still bares some resemblance to my original code will be welcome!
First, c.show() prints the list, but you haven't defined __str__ or __repr__ for your classes, so you're stuck with the default representation. Try e.g.
def __str__(self):
return str(self.name)
Then you can:
print(map(str, self.items))
Alternatively, use your item.show:
for i in self.items:
i.show()
Second, in checkOut, i is an item, which you can't index into. If you want its price, use dot notation: i.price.