简体   繁体   中英

How to use if statements in classes

I'm trying to make a simple library where the user can add and remove books from his shopping cart, but I don't know how to use if statements with OOP and classes.

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)

I don't know if this is the right way to use the if statement with classes so if you can just give me an example to show how it's done correctly?

when you said "fonction", I think you mean "function". When you make a try: block, you must also add an except: block. Also, don't put code directly in the class. Put it inside a function (aka methods). I put the code starting from # sign in the __int__ method. We generally don't put methods (functions) inside other methods. So, put the __str__ and __iadd__ methods outside the __init__ method . To call it, use self.__str__() and self.__iadd__() .

Here is the updated code:

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)

OK, I have rewritten your code to implement it in a more organized way. Your class "library" was not really a library at all; it is a class for "orders", and I have renamed it as such. I didn't know what you wanted for the manager account, so the manager account just assigns a fake user name without requiring a signup. I also fixed the spelling errors and the tabbing.

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

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