简体   繁体   中英

Appending an instance issues in python

Having some problems with append(). The intended functionality: User chooses to input car data of print data. If input data is selected, user is asked to provide car make and MSRP. The input is to be stored. When user choses to print - programme will provide a list of the previous inputs (make and list price). What i made is below.

class CARDATA:
brand = ""
price = ""

def menu():
    print("1) Input car data")
    print("2) Print car data")
    option = int(input("Your pick was: "))
    return option

def car_object(car_description):
    car = CARDATA() 
    car.brand = input("Car make?: ")
    car.price = int(input("Listed price? "))
    car_description.append(car)
    return car

def main():
    car_description = []
    while (True):
        selection = menu()
        if (selection == 1):
            car = car_object(car_description)
            #car_description.append(car)    
        elif (selection == 2):
            print("Car makes and selling prices on the list:")
            for vehicle in car_description:
                print(car.brand, car.price)
    return car_description

main ()

It looks like my list is being overwritten somewhere, as I am storing only the last car make/price. What I want is to have the programme print out all of the car makes/prices what were fed to it. I thought the issue was in the main(), but it looks like my list is initialized well before the for loop begins. The problem seems to be somewhere else. I am not sure what am I not seeing.

You forgot to make tabs in CARDATA class. When I added them, it works normally:

class CARDATA:
    brand = ""
    price = ""

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