How can I define an object in this cart method without overwriting the previous one?
Question:
I am coding a Shopping Website in Python, and am having trouble with the 4th option in the code, the checkout, since if a user tries to checkout without entering any data in, it will give an error, and I’m not sure how to fix this, since if I just make a cart, it will overwrite the data. Here is the code –
#Created by Aykhan Salimov on 09.22.2020
#This is a class for books
class Book:
def __init__(self, number, title, author, genre, price):
self.number = number
self.title = title
self.author = author
self.genre = genre
self.price = price
def __str__(self):
return "This book's name is " + self.title + "n" + "This book's author is " + self.author + "n" + "This book's genre is " + self.genre + "n" + "This book's price is " + self.price
#This is a class for the inventory of books for sale
class Inventory:
def __init__(self, make):
self.make = make
def books(self):
print("Current Books")
f.open = open("booklist.txt", "r")
f.read()
f.close()
def add_book(self):
print("Please specify the book information for the book you wish to add")
addbookn = input("Please input the number of the book you wish to add: ")
addbookt = input("Please input the title of the book you wish to add: ")
addbooka = input("Please input the author of the book you wish to add: ")
addbookg = input("Please input the genre of the book you wish to add: ")
addbookp = input("Please input the price of the book you wish to add: ")
newBook = Book(addbookn, addbookt, addbooka, addbookg, addbookp)
f.open = open("booklist.txt", "r")
f.write("/n%s" % newBook)
def display(self):
print("===========================================")
print("Item number:", book0.number)
print("Title:", book0.title)
print("Author:", book0.author)
print("Genre:", book0.genre)
print("Price:", book0.price)
print("===========================================")
print("Item number:", book1.number)
print("Title:", book1.title)
print("Author:", book1.author)
print("Genre:", book1.genre)
print("Price:", book1.price)
print("===========================================")
print("Item number:", book2.number)
print("Title:", book2.title)
print("Author:", book2.author)
print("Genre:", book2.genre)
print("Price:", book2.price)
print("===========================================")
print("Item number:", book3.number)
print("Title:", book3.title)
print("Author:", book3.author)
print("Genre:", book3.genre)
print("Price:", book3.price)
print("===========================================")
print("Item number:", book4.number)
print("Title:", book4.title)
print("Author:", book4.author)
print("Genre:", book4.genre)
print("Price:", book4.price)
print("===========================================")
#This is a class for the user's cart
class Cart(Inventory):
def add_book(self):
numberbook = int(input("What is the number of the book you would like to buy?"))
self.cartlist = []
if numberbook == 1000:
self.cartlist.append(23.99)
if numberbook == 1001:
self.cartlist.append(3.99)
if numberbook == 1002:
self.cartlist.append(3.99)
if numberbook == 1003:
self.cartlist.append(9.99)
if numberbook == 1004:
self.cartlist.append(61.99)
if numberbook <= 999 or numberbook >= 1005:
print("You made a wrong selection")
return self.cartlist
def checkout(self):
total = sum(self.cartlist)
print("Thank you for shopping! Your total is:", total)
return self.cartlist
return self.cartlistfh
book0 = Book("1000", "Science: A Visual Encyclopedia", "Chris Woodford", "Science", "$23.99")
book1 = Book("1001", "My First Human Body Book", "Patricia J. Wyennevand Donald M Silver", "Science", "$3.99")
book2 = Book("1002", "The Runaway Children", "Sandy Taylor", "Fiction", "$9.99")
book3 = Book("1003", "The Tuscan Child", "Rhys Bowen", "Fiction", "$9.99")
book4 = Book("1004", "Science: A Visual Encyclopedia", "Chris Woodford", "Science", "$23.99")
loop = True
while(loop):
print("1: Display Books")
print("2: Add to Cart")
print("3: Show Cart")
print("4: Checkout")
print("5: Quit")
userinput = str(input("Select an Option: "))
if userinput == '1':
myInventory = Inventory("Inventory")
myInventory.display()
print("These are the book for sale")
print("You will now be returned to the home screen")
continue
if userinput == '2':
loop2 = True
while(loop2):
myCart = Cart("Cart")
myCart.add_book()
print("Book(s) added successfully!")
userin2 = str(input("Would you like to continue buying books? Type 1 if yes and 2 if no!"))
if userin2 == '1':
print("OK! Let's continue")
continue
if userin2 == '2':
print("OK. You will now be returned to the home screen")
loop2 = False
continue
if userinput == '3':
#Work in progress
print(".")
continue
if userinput == '4':
#Issues with this method, since creating a new object doesn't have the previous one's information, and this code gives an error if the cart is blank
myCart.checkout()
loop = False
if userinput == '5':
print("Thank you for shopping!")
loop = False
Answers:
Right now, you have a couple of problems. The first is that every time you call Cart’s add_book
function, you overwriting the list of books. The easiest way to fix this is to move cartlist
to Cart’s __init__
method. You can do this without losing the functionality of Inventory’s __init__
with a call to super, like so:
def __init__(self, make):
super().__init__(make)
self.cartlist = []
If you are not familiar, super()
is a way to reference the parent class of an object, in this case Inventory.
The second issue with your code is that you are creating a new cart every time someone selects option 2. This, again, wipes cartlist
, since a new cart will have an empty cartlist
. I would recommend moving the instantiation of myCart
(and myInventory
, for that matter) up above the while loop where you define all of your books. That way, these objects will only be created once, and you won’t run into issues trying to check out before the cart is created.
I am coding a Shopping Website in Python, and am having trouble with the 4th option in the code, the checkout, since if a user tries to checkout without entering any data in, it will give an error, and I’m not sure how to fix this, since if I just make a cart, it will overwrite the data. Here is the code –
#Created by Aykhan Salimov on 09.22.2020
#This is a class for books
class Book:
def __init__(self, number, title, author, genre, price):
self.number = number
self.title = title
self.author = author
self.genre = genre
self.price = price
def __str__(self):
return "This book's name is " + self.title + "n" + "This book's author is " + self.author + "n" + "This book's genre is " + self.genre + "n" + "This book's price is " + self.price
#This is a class for the inventory of books for sale
class Inventory:
def __init__(self, make):
self.make = make
def books(self):
print("Current Books")
f.open = open("booklist.txt", "r")
f.read()
f.close()
def add_book(self):
print("Please specify the book information for the book you wish to add")
addbookn = input("Please input the number of the book you wish to add: ")
addbookt = input("Please input the title of the book you wish to add: ")
addbooka = input("Please input the author of the book you wish to add: ")
addbookg = input("Please input the genre of the book you wish to add: ")
addbookp = input("Please input the price of the book you wish to add: ")
newBook = Book(addbookn, addbookt, addbooka, addbookg, addbookp)
f.open = open("booklist.txt", "r")
f.write("/n%s" % newBook)
def display(self):
print("===========================================")
print("Item number:", book0.number)
print("Title:", book0.title)
print("Author:", book0.author)
print("Genre:", book0.genre)
print("Price:", book0.price)
print("===========================================")
print("Item number:", book1.number)
print("Title:", book1.title)
print("Author:", book1.author)
print("Genre:", book1.genre)
print("Price:", book1.price)
print("===========================================")
print("Item number:", book2.number)
print("Title:", book2.title)
print("Author:", book2.author)
print("Genre:", book2.genre)
print("Price:", book2.price)
print("===========================================")
print("Item number:", book3.number)
print("Title:", book3.title)
print("Author:", book3.author)
print("Genre:", book3.genre)
print("Price:", book3.price)
print("===========================================")
print("Item number:", book4.number)
print("Title:", book4.title)
print("Author:", book4.author)
print("Genre:", book4.genre)
print("Price:", book4.price)
print("===========================================")
#This is a class for the user's cart
class Cart(Inventory):
def add_book(self):
numberbook = int(input("What is the number of the book you would like to buy?"))
self.cartlist = []
if numberbook == 1000:
self.cartlist.append(23.99)
if numberbook == 1001:
self.cartlist.append(3.99)
if numberbook == 1002:
self.cartlist.append(3.99)
if numberbook == 1003:
self.cartlist.append(9.99)
if numberbook == 1004:
self.cartlist.append(61.99)
if numberbook <= 999 or numberbook >= 1005:
print("You made a wrong selection")
return self.cartlist
def checkout(self):
total = sum(self.cartlist)
print("Thank you for shopping! Your total is:", total)
return self.cartlist
return self.cartlistfh
book0 = Book("1000", "Science: A Visual Encyclopedia", "Chris Woodford", "Science", "$23.99")
book1 = Book("1001", "My First Human Body Book", "Patricia J. Wyennevand Donald M Silver", "Science", "$3.99")
book2 = Book("1002", "The Runaway Children", "Sandy Taylor", "Fiction", "$9.99")
book3 = Book("1003", "The Tuscan Child", "Rhys Bowen", "Fiction", "$9.99")
book4 = Book("1004", "Science: A Visual Encyclopedia", "Chris Woodford", "Science", "$23.99")
loop = True
while(loop):
print("1: Display Books")
print("2: Add to Cart")
print("3: Show Cart")
print("4: Checkout")
print("5: Quit")
userinput = str(input("Select an Option: "))
if userinput == '1':
myInventory = Inventory("Inventory")
myInventory.display()
print("These are the book for sale")
print("You will now be returned to the home screen")
continue
if userinput == '2':
loop2 = True
while(loop2):
myCart = Cart("Cart")
myCart.add_book()
print("Book(s) added successfully!")
userin2 = str(input("Would you like to continue buying books? Type 1 if yes and 2 if no!"))
if userin2 == '1':
print("OK! Let's continue")
continue
if userin2 == '2':
print("OK. You will now be returned to the home screen")
loop2 = False
continue
if userinput == '3':
#Work in progress
print(".")
continue
if userinput == '4':
#Issues with this method, since creating a new object doesn't have the previous one's information, and this code gives an error if the cart is blank
myCart.checkout()
loop = False
if userinput == '5':
print("Thank you for shopping!")
loop = False
Right now, you have a couple of problems. The first is that every time you call Cart’s add_book
function, you overwriting the list of books. The easiest way to fix this is to move cartlist
to Cart’s __init__
method. You can do this without losing the functionality of Inventory’s __init__
with a call to super, like so:
def __init__(self, make):
super().__init__(make)
self.cartlist = []
If you are not familiar, super()
is a way to reference the parent class of an object, in this case Inventory.
The second issue with your code is that you are creating a new cart every time someone selects option 2. This, again, wipes cartlist
, since a new cart will have an empty cartlist
. I would recommend moving the instantiation of myCart
(and myInventory
, for that matter) up above the while loop where you define all of your books. That way, these objects will only be created once, and you won’t run into issues trying to check out before the cart is created.