首页 > 解决方案 > 在 Python 中导出为文本

问题描述

如果用户选择该选项,我的部分任务是导出为文本。除了那一部分,我似乎什么都做对了。谁能建议我哪里出错了?我是否需要在代码中的其他地方添加一些东西才能正常工作?automobilelist选择选项 6 时出现未定义的错误。

class Automobile:
    # constructor, it takes parameters make, model, year and mileage
    def __init__(self,aMake,aModel,aColor,aYear,aMileage):
        # assign passed values to instance variables
        self.setMake(aMake)  # string
        self.setModel(aModel)  # string
        self.setColor(aColor) # string
        self.setYear(aYear)   # int
        self.setMileage(aMileage)  # int

    # setter of make
    # it takes 1 parameter make
    # it doesn't returns anything
    def setMake(self, aMake):
        self.__make = aMake

    # getter of make
    # it doesn't take any parameters
    # it returns make
    def getMake(self):
        return self.__make

    # setter of model
    # it takes 1 parameter model
    # it doesn't returns anything
    def setModel(self, aModel):
        self.__model = aModel

    # getter of model
    # it doesn't take any parameters
    # it returns model
    def getModel(self):
        return self.__model

    # setter of color
    # it takes 1 parameter color
    # it doesn't returns anything
    def setColor(self, aColor):
        self.__color = aColor
        return True

    # getter of color
    # it doesn't take any parameters
    # it returns color
    def getColor(self):
        return self.__color

    # setter of year
    # it takes 1 parameter year
    # it doesn't returns anything
    def setYear(self, aYear):
        self.__year = aYear

    # getter of year
    # it doesn't take any parameters
    # it returns year
    def getYear(self):
        return self.__year

    # setter of mileage
    # it takes 1 parameter year
    # it doesn't returns anything
    def setMileage(self, aMileage):
        self.__mileage = aMileage

    # getter of mileage
    # it doesn't take any parameters
    # it returns mileage
    def getMileage(self):
        return self.__mileage

    # string representation of the instance variables
    # it doesn't take any parameters
    # it returns string form of object
    def __str__(self):
        return "{}, {}, {}, {}, {}".format(self.getMake(),self.getModel(),self.getColor(),self.getYear(),self.getMileage())

class Automobiledealership:

    # constructor
    # it initializes the empty automobile list
    def __init__(self):
        self.__automobilelist = []

    # adds automobile to dealership
    # it takes automobile class object as parameter
    # it doesn't returns anything
    def addAutomobile(self, automobile):
        self.__automobilelist.append(automobile)

    # removes automobile from dealership
    # it takes index of automobile in the list as parameter
    # it doesn't returns anything
    def removeAutomobile(self, index):
        del self.__automobilelist[index-1]

    # returns automobile from dealership
    # it takes index of automobile in the list as parameter
    # it returns automobile object located at that index
    def getAutomobile(self, index):
        return self.__automobilelist[index-1]

    # prints the list of automobiles
    # it doesn't take any parameters
    # it doesn't returns anything
    def printAutomobileList(self):
        if len(self.__automobilelist)==0:
            print("No automobiles in dealership")
        else:
            for i in range(len(self.__automobilelist)):
                print("{}. {}".format(i+1,self.__automobilelist[i]))


    # add some automobiles to the dealership for Sample Inventory
def addSampleAutomobiles(automobiles):
    automobiles.addAutomobile(Automobile("Ford", "Focus", "Red", 2019, 8000))
    automobiles.addAutomobile(Automobile("Toyota","Corolla","White",2007,65000))
    automobiles.addAutomobile(Automobile("Ford","Endura","Black",2019,5000))
    automobiles.addAutomobile(Automobile("Audio","A1","White",2016,23000))
    automobiles.addAutomobile(Automobile("Toyota", "Camry", "Red", 2000, 25000))
    automobiles.addAutomobile(Automobile("Ford","Everest","Black",2017,16000))
    automobiles.addAutomobile(Automobile("Mazda","MX5","Red",2015,33000))
    automobiles.addAutomobile(Automobile("Ford","Escape","Grey",2018,15000))
    automobiles.addAutomobile(Automobile("Toyota", "Prius", "Red", 2010, 35000))

def addAutomobile(automobiles):
    make = input("Please enter Make >> ")
    model = input("Please enter Model >> ")
    color = input("Please enter Color >> ")
    year = int(input("Please enter Year >> "))
    mileage = int(input("Please enter Mileage >> "))
    automobiles.addAutomobile(Automobile(make,model,color,year,mileage))

def removeAutomobile(automobiles):
    index = int(input("Please enter number of the automobile to be removed >> "))
    automobiles.removeAutomobile(index)

def updateAutomobile(automobiles):
    index = int(input("Please enter number of the automobile to be updated >> "))
    automobile = automobiles.getAutomobile(index)
    make = input("Please enter Make (enter 0 to skip) >> ")
    model = input("Please enter Model (enter 0 to skip) >> ")
    color = input("Please enter Color (enter 0 to skip) >> ")
    year = int(input("Please enter Year (enter 0 to skip) >> "))
    mileage = int(input("Please enter Mileage (enter -1 to skip) >> "))
    if make!='0':
        automobile.setMake(make)
        print("Automobile make is updated")
    if model!='0':
        automobile.setModel(model)
        print("Automobile model is updated")
    if color!='0':
        automobile.setColor(color)
        print("Automobile color is updated")
    if year!=0:
        automobile.setYear(year)
        print("Automobile year is updated")
    if mileage!=-1:
        automobile.setMileage(mileage)
        print("Automobile mileage is updated")

    # create automobile dealership object
automobiles = Automobiledealership()
choice = -1
    # start loop
while choice!=0:
    print()
    print("1. Add sample automobiles to dealership")
    print("2. Display automobiles in the dealership")
    print("3. Add automobile to dealership")
    print("4. Remove automobile from dealership")
    print("5. Update automobile at dealership")
    print("6. Export automobile Inventory")
    print("0. Exit program")

    choice = int(input("Your choice >> "))
    print()

    if choice==1:
        addSampleAutomobiles(automobiles)
    elif choice==2:
        automobiles.printAutomobileList()
    elif choice==3:
        addAutomobile(automobiles)
    elif choice == 4:
        removeAutomobile(automobiles)
    elif choice == 5:
        updateAutomobile(automobiles)
    elif choice == 6:
        f = open('AutomobileList.txt', 'w')
        f.write(str(automobilelist))
        f.close()

标签: pythontextexport

解决方案


你得到这个错误是因为汽车列表实际上没有在汽车经销商类的范围之外定义。

如果你想从一个类中获取字段,你应该调用 < InstanceName >.< FieldName >,在你的例子中是automobiles.__automobilelist.

但在你的情况下,它仍然不起作用。当您为__automobilelist添加双下划线前缀时,您将其定义为汽车经销商类的私有成员,因此您还应该为汽车列表创建一个 getter 函数(就像您对getAutomobile所做的那样)

一个简单的 getter 函数,你可以在你的类中使用:

def getAutoMobileList(self):
    return self.__automobilelist

然后调用automobiles.getAutoMobileList().

解决此问题的另一种方法:

你叫str(automobilelist)了,上面说的应该是str(automobiles.getAutoMobileList()),又可以翻译成automobiles.__str__()。这意味着您可以定义一个__str__函数,而不是上面提到的 getter 函数。因此,对于换行符分隔值,您可以定义:

def __str__(self):
    return '\n'.join(str(i) for i in self.__automobilelist)

然后打电话str(automobiles)


推荐阅读