В ООП Python, как метод может влиять на переменную - PullRequest
0 голосов
/ 24 сентября 2019

Я создаю книжный магазин на Python и пытаюсь определить переменную с именем total_price, которая будет принимать цену каждой книги и количество книг, которые нужно умножить, чтобы затем хранить ее.Также я пытаюсь сломать мой код, когда пользователь нажимает 5 или Quit.Кстати, мне 13 лет, и я пытаюсь научиться кодировать, извините, если этот вопрос не соответствует вашим стандартам.

#The following code will be a bookstore
cart = []
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:
    #This code calls the book class
    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)
    #This part print each of the books
    print(book1)
    print(book2)
    print(book3)
    print(book4)
    print(book5)
class Inventory:
    books = {1000 : "A visual Encyclopedia", 1001 : "My First Human Body Book", 1002 : "The Runaway Children", 1003 : "The Tuscan Child", 1004 : "Learning Python"}

    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):
    books = ""
    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 += float(how_many_books) * 23.99
            cart.append(str(to_buy_books) + "*" + str(how_many_books))
        elif to_buy_books == 1001:
            total_price += how_many_books * 3.99
            cart.append(str(to_buy_books) + "*" + str(how_many_books))
        elif to_buy_books == 1002:
            total_price += how_many_books * 3.99
            cart.append(str(to_buy_books) + "*" + str(how_many_books))

        elif to_buy_books == 1003:
            total_price += how_many_books * 9.99
            cart.append(str(to_buy_books) + "*" + str(how_many_books))

        else:
            total_price += how_many_books * 61.99
            cart.append(str(to_buy_books) + "*" + str(how_many_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()
    cart1.add_book()
elif menu == 3:
    if len(cart) == 0:
        print("Cart is empty")
    else:
        print(str(cart))
elif menu == 4:
    print(total_price)
else:
    ask = False


stop()

Когда я запускаю этот код, он говорит, что ошибка total_price не определена.Есть мысли?

Отредактированный код:

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:
    #This code calls the book class
    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)
    #This part print each of the books
    print(book1)
    print(book2)
    print(book3)
    print(book4)
    print(book5)
class Inventory:
    books = {1000 : "A visual Encyclopedia", 1001 : "My First Human Body Book", 1002 : "The Runaway Children", 1003 : "The Tuscan Child", 1004 : "Learning Python"}

    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):
    def __init__(self):
        self.total_price = 0
    def __str__(self):
        return str(self.total_price)
    books = ""
    def add_book(self):
        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:
            self.total_price += float(how_many_books) * 23.99
            cart.append(str(to_buy_books) + "*" + str(how_many_books))
        elif to_buy_books == 1001:
            self.total_price += float(how_many_books) * 3.99
            cart.append(str(to_buy_books) + "*" + str(how_many_books))
        elif to_buy_books == 1002:
            self.total_price += float(how_many_books) * 3.99
            cart.append(str(to_buy_books) + "*" + str(how_many_books))

        elif to_buy_books == 1003:
            self.total_price += float(how_many_books) * 9.99
            cart.append(str(to_buy_books) + "*" + str(how_many_books))

        else:
            self.total_price += float(how_many_books) * 61.99
            cart.append(str(to_buy_books) + "*" + str(how_many_books))




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

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


stop()
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...