简体   繁体   English

在 python 中附加实例问题

[英]Appending an instance issues in python

Having some problems with append(). 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.我认为问题出在 main() 中,但看起来我的列表在 for 循环开始之前就已经初始化好了。 The problem seems to be somewhere else.问题似乎出在其他地方。 I am not sure what am I not seeing.我不确定我没有看到什么。

You forgot to make tabs in CARDATA class.您忘记在CARDATA类中制作标签。 When I added them, it works normally:当我添加它们时,它正常工作:

class CARDATA:
    brand = ""
    price = ""

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM