简体   繁体   中英

How to use Objects in Python effectively

So I am trying to create a virtual book store and when I run my code I keep getting an error.

ask = True
def stop():
while ask:
    stop_or_no()

def stop_or_no():
menu = int(input(" 1: Display Books \n 2: Add to cart: \n 3 Show cart  \n 4: Checkout \n 5: Quit \nSelect an option in number form: "))


class Book:
    def __init__(self,title,author,genre,price):
        self.title = title
        self.author = author
        self.genre = genre
        self.price = price
    def __str__(self):
        return self.title + "," + self.author + "," + self.genre + "," + str(float(self.price))
if menu == 1:

    book1 = Book("A visual Encyclopedia","Chris Woodford", "Science", 23.99)
    book2 = Book("My First Human Body Book", "Patricia J. Wynne and Donald M. Silver","Science", 3.99)
    book3 = Book("The Runaway Children", "Sandy Taylor","Fiction", 3.99)
    book4 = Book("The Tuscan Child", "Rhys Bowen","Fiction", 9.99)
    book5 = Book("Learning Python", "Mark Lutz","Programming", 61.99)
class Inventory:
    books = {1000 : str(book1), 1001 : str(book2), 1002 : str(book3), 1003 : str(book4), 1004 : str(book5)}
    print(books)

    def add_book1(self):
        book_list = open("C:\\Users\\brian\\Documents\\Coding\\booklist.txt")
        print(book_list.read())
    def display(self):
        print(books)
class Cart(Inventory):
    cart = []
    def add_book(self):
        total_price = 0
        to_buy_books = int(input("What is the item number you would like to buy?"))
        how_many_books = input("How many of that item would you like to buy?") 
        if to_buy_books == 1000:
            total_price += how_many_books * 23.99
            cart.append(to_buy_books)
        elif to_buy_books == 1001:
            total_price += how_many_books * 3.99
        elif to_buy_books == 1002:
            total_price += how_many_books * 3.99
            cart.append(to_buy_books)
        elif to_buy_books == 1003:
            total_price += how_many_books * 9.99
            cart.append(to_buy_books)
        else:
            total_price += how_many_books * 61.99
            cart.append(to_buy_books)



    def checkout(self):
        if total_price == 0:
            print("There is nothing in your cart")
        else:
            print(total_price)
            print("Thank you for shopping with us today! Please come back again!")

if menu == 2:
    cart1 = Cart.add_book
elif menu == 3:
    if len(cart) == 0:
        print("Cart is empty")
    else:
        print(str(cart))
elif menu == 4:
    Cart.checkout
else:
    ask = False
    print("Thank you for using this application")


stop()

I expected the code to run smoothly, but when I run it, it prints this error message:

Traceback (most recent call last):
  File "C:\Users\brian\Documents\Coding\FinalProject_Bmason1270130.py", line 81, in <module>
    stop()
  File "C:\Users\brian\Documents\Coding\FinalProject_Bmason1270130.py", line 7, in stop
    stop_or_no()
  File "C:\Users\brian\Documents\Coding\FinalProject_Bmason1270130.py", line 28, in stop_or_no
    class Inventory:
  File "C:\Users\brian\Documents\Coding\FinalProject_Bmason1270130.py", line 29, in Inventory
    books = {1000 : str(book1), 1001 : str(book2), 1002 : str(book3), 1003 : str(book4), 1004 : str(book5)}
NameError: free variable 'book1' referenced before assignment in enclosing scope

You define book1 if menu == 1, but if menu,= 1. then book1 is undefined, Next You define a class Inventory, which has a class variable, that uses book1. which if menu,= 1 is undefined. Keep in mind that class variables get evaluated when class is defined, as you can see in this example.

class Obj:
    var = print('var init')

which immediately prints 'var init'. Just define book1, …, book5 in any scope you will need them.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM