如何将一个简单的Python程序从使用函数转化为类[关闭] 。

问题描述 投票:0回答:1

我尝试了一个学生的挑战,就是写一个程序,将。

  1. 允许用户将书籍添加到他们的图书馆
  2. 打印他们的图书馆
  3. 使用不同的参数搜索图书馆中的书籍

我的程序可以让我实现上述所有要求,但是我是通过使用函数来实现的。 我怎样才能用类来代替写这个程序,这比函数有什么优势?

程序的主体

#Assign default variables
x = True
z = True
aa = True
book_list = []

#Import module and functions
from bookstoreage_test import add_books, main_menu, continue_loop, search_books

#Start loop of program main menu
while z is True:
 option = main_menu()

#Add books to list
 if option =="1":
    while x is True:
        book_list.append(add_books())
        x=continue_loop()

#Print list of books - non looping, will end program after printing list
 elif option=="2":
    print(book_list)
    break

#Allows users to search for a book
 elif option =="3":
   # while aa is True:
    search=input("Find name of a book by: (name=1, author=2, genre=3 or list books available in each category = 4))")
    search_input = input("Please enter in the search value")

    if search == str(1) or str(2) or str(3):
        r = search_books(book_list,search_input)
        print (r)
    z=continue_loop()

 else:
     print("You selected an invalid input")

程序主体中使用的函数库。

#Adding books to a dictionary through user input
def add_books():
    books_stored3 = {
      'name': input("What is the name of the book? "),
      'author': input("Who is the author? "),
      'genre': input("What is the book genre")
    }
    return (books_stored3)

#Main menu - Asks user for how they would like to proceed
def main_menu():
    print("\nWelcome to your books storage.  Please selection from one of the following options\n")
    user_choice = input(" 1. Add new books to collection. \n 2. View all books in collection. \n 3. Find a book within collection\n")
    return(user_choice)

#Option to continue items to the list or return to main menu
def continue_loop():
    contd = True
    con_loop = input("Do you want to continue (Y/N) ")
    if con_loop.lower()=="y":
        contd = True
    else:
        contd=False
    return (contd)


def search_books(book_list,search_input):
    t=[]

    for pairs in book_list:
        for key, value in pairs.items():
            if search_input.lower() == value.lower():
                t.append([(pairs['name'])])

            elif search_input.lower() in key:
                t.append(value)
    return t
python function loops class conditional-statements
1个回答
1
投票

我修改了一下你的代码。我定义了一个名为库的类,它包括所有的功能,现在作为类的方法。此外,我插入了几行代码,以这种方式,用户可以决定是否留在选项菜单或退出,而不仅仅是如果他想留在特定的选项1,2或3。

我认为类和函数之间的区别只是一个方便性的问题,有时用类写代码更直观,但从性能的角度来看,它并没有带来真正的好处,唯一真正的区别是你现在可以访问类的方法,也就是说,你可以利用你已经创建的函数,甚至在主程序之外。

我把**和**之间的链式连接放在了一起。

x = True
z = True
aa = True
book_list = []

**class library():**

    **def __init__(self, option=1): 
        self.option = option** 

    #Main menu - Asks user for how they would like to proceed
    def main_menu(self):
        print("\nWelcome to your books storage.  Please selection from one of the following options\n")
        user_choice = input(" 1. Add new books to collection. \n 2. View all books in collection. \n 3. Find a book within collection\n")
        **self.option = user_choice** 

    def add_books(self):
        books_stored3 = {'name': input("What is the name of the book? "), 'author': input("Who is the author? "),'genre': input("What is the book genre")}
        return (books_stored3)

    #Option to continue items to the list or return to main menu
    def continue_loop(self):
        contd = True
        con_loop = input("Do you want to continue (Y/N) ")
        if con_loop.lower()=="y":
            contd = True
        else:
            contd=False
        return (contd)

    def search_books(self, book_list,search_input):
        t=[]

        for pairs in book_list:
            for key, value in pairs.items():
                if search_input.lower() == value.lower():
                    t.append([(pairs['name'])])

                elif search_input.lower() in key:
                    t.append(value)
        return t

#main program
**library = library()**

while z is True:
    **ex = input('Do you want exit from library ? y/n ')**
    **if ex.lower() == 'y':
        break**
    library.main_menu()
#Add books to list
    if library.option == "1":
        while x is True:
            book_list.append(**library.add_books()**)
            x=**library.continue_loop()**
    #Print list of books - non looping, will end program after printing list
    elif **library.option**=="2":
        print(book_list)

#Allows users to search for a book
    elif **library.option** =="3": 
        **while aa is True:**
            search=input("Find name of a book by: (name=1, author=2, genre=3 or list books available in each category = 4))")
            search_input = input("Please enter in the search value")

            if search == str(1) or str(2) or str(3):
                r = **library.search_books(book_list,search_input)**
                print (r)
            **aa=library.continue_loop()**

    else:
        print("You selected an invalid input")





© www.soinside.com 2019 - 2024. All rights reserved.