簡體   English   中英

如何在類中使用 if 語句

[英]How to use if statements in classes

我正在嘗試創建一個簡單的庫,用戶可以在其中添加和刪除購物車中的書籍,但我不知道如何使用帶有 OOP 和類的 if 語句。

try:
 class library:
     def __init__(self, books, customer):
         self.books = books
         self.customer = customer
    # sign:
     check = input("manager account(1), customer account(2): ")

     if check == "2":
    #age >= 18
         age = int(input("enter your age:  "))   
         if age >= 18:
            #name
             name = input("enter your firstname: ")

            # ID
             import random
             x = "ID"+str(random.randint(101,999))
             print(f"your ID is: {x}")
             print("you should memorize it")
             y = input("enter password that has at list 8 caracterse: ")

            # Password
             while len(y) < 8:
                 y = input("enter password that has at list 8 caracterse: ")
                 print(f"your password is: {y}")
             print("you should memorize it")
             data = [x,y]
             choice_1 = input("check your shopping cart(1): \nadd books to your shopping cart(2): \nremove books from your shopping cart(3): ")
             if choice_1 == "1":
                 def __str__(self):
                    return f"customer {self.customer} bought those books{self.books}"
             elif choice_1 == "2":
                 def __iadd__(self, other):
                     self.books.append(other)
                     return self

 order = library(["the golsen company"],"Mr.asad")
 print(order.books)
 order += input("enter a book: ")
 print(order.books)
except ValueError as ages:
    print(ages)

我不知道這是否是將if語句與類一起使用的正確方法,所以如果你能給我一個例子來說明它是如何正確完成的?

當您說“功能”時,我認為您的意思是“功能”。 當您try:塊時,您還必須添加一個except:塊。 另外,不要將代碼直接放在 class 中。 將其放入 function(又名方法)中。 我把從# sign開始的代碼放到了__int__方法中。 我們一般不會把方法(函數)放在其他方法里面。 因此,將__str____iadd__方法放在__init__ method之外。 要調用它,請使用self.__str__()self.__iadd__()

這是更新的代碼:

try:
    class library:
        def __init__(self, books, customer):
            self.books = books
            self.customer = customer

            # sign:
            check = input("manager account(1), customer account(2): ")

            if check == "2":
                # age >= 18
                age = int(input("enter your age:  "))
                if age >= 18:
                    # name
                    name = input("enter your firstname: ")

                    # ID
                    import random
                    x = "ID" + str(random.randint(101, 999))
                    print(f"your ID is: {x}")
                    print("you should memorize it")
                    y = input("enter password that has at list 8 caracterse: ")

                    # Password
                    while len(y) < 8:
                        y = input("enter password that has at list 8 caracterse: ")
                        print(f"your password is: {y}")
                    print("you should memorize it")
                    data = [x, y]
                    choice_1 = input("check your shopping cart(1): \nadd books to your shopping cart(2): ")
                    if choice_1 == "1":
                        self.__str__()

                    elif choice_1 == "2":
                        self.__iadd__()

                # age < 18
                elif age < 18:
                    print("this library is not for your age")

        def __iadd__(self, other):
            self.books.append(other)
            return self

        def __str__(self):
            return f"customer {self.customer} bought those books{self.books}"
except:
    pass

order = library(["the golsen company"], "Mr.asad")
print(order.books)
order += input("enter a book: ")
print(order.books)

好的,我已經重寫了你的代碼,以更有條理的方式實現它。 您的 class “庫”根本不是真正的庫; 它是“訂單”的 class,我已將其重命名為。 我不知道您對經理帳戶的要求是什么,因此經理帳戶只是分配了一個假用戶名,而無需注冊。 我還修復了拼寫錯誤和標簽。

import random
import sys

class Order:
    def __init__(self, books, customer):
        self.books = books
        self.customer = customer
    def __iadd__(self, other):
        self.books.append(other)
        return self
    def __isub__(self, other):
        self.books.remove(other)
        return self
    def __str__(self):
        return f"custumer {self.customer} bought those books {self.books}"

# sign in.

check = input("manager account(1),custumer account(2): ")

if check == '1':
    x = 'manager'

if check == "2":
    #age >= 18

    age = int(input("enter your age:  "))   
    if age < 18:
        print("Sorry, you must be at least 18.")
        sys.exit(0)

    #name
    name = input("enter your firstname: ")

    # ID
    x = "ID"+str(random.randint(101,999))
    print(f"your ID is: {x}")
    print("you should memorize it")

    # Password
    y = input("enter password that has at least 8 characters: ")
    while len(y) < 8:
        y = input("enter password that has at least 8 characters: ")
    print(f"your password is: {y}")
    print("you should memorize it")

# Main menu.

order = Order( [], x )

while True:
    print('---')
    choice_1 = input("1. check your shopping cart\n2. add books to your shopping cart\n3. remove books from your shopping cart\n4. quit: ")
    if choice_1 == "1":
        print( order )
    elif choice_1 == "2":
        order += input("enter a book: ")
    elif choice_1 == "3":
        book = input("enter a book: ")
        if book in order.books:
            order -= book
        else:
            print( f"{book} is not in your cart." )
    elif choice_1 == "4":
        break

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM