首页 > 解决方案 > 在这个程序中我得到属性错误?谁能解决这个错误并向我解释

问题描述

这是一个小型汽车经销商的简单库存程序。

print('Automotive Inventory')

class Automobile:
    def _init_(self):
        self._make = ''
        self._model = ''
        self._year = 0
        self._color = ''
        self._mileage = 0
    def addVehicle(self):
        try:
            self._make = input('Enter vehicle make: ')
            self._model = input('Enter vehicle model: ')
            self._year = int(input('Enter vehicle year: '))
            self._color = input('Enter vehicle color: ')
            self._mileage = int(input('Enter vehicle mileage: '))
            return True
        except ValueError:
            print('Please try entering vehicle information again using only whole numbers for mileage and year')
            return False
    def _str_(self):
        return '\t'.join(str(x) for x in [self._make, self._model, self._year, self._color, self._mileage])
class Inventory(Automobile):
    def _init_(self):
        self.vehicles = []
    def addVehicle(self):

        vehicle = Automobile()
        if vehicle.addVehicle() == True:
            self.vehicles.append(vehicle)
            print ()
            print('This vehicle has been added, Thank you')
    def viewInventory(self):
        print('\t'.join(['','Make', 'Model','Year', 'Color', 'Mileage']))
        for idx, vehicle in enumerate(self.vehicles) :
            print(idx + 1, end='\t')
            print(vehicle)


inventory = Inventory()
while True:

    print('#1 Add Vehicle to Inventory')
    print('#2 Delete Vehicle from Inventory')
    print('#3 View Current Inventory')
    print('#4 Update Vehicle in Inventory')
    print('#5 Export Current Inventory')
    print('#6 Quit')
    userInput=input('Please choose from one of the above options: ')
    if userInput=="1":
        #add a vehicle
        inventory.addVehicle()
    elif userInput=='2':
        #delete a vehicle
        if len(inventory.vehicles) < 1:
            print('Sorry there are no vehicles currently in inventory')
            continue
        inventory.viewInventory()
        item = int(input('Please enter the number associated with the vehicle to be removed: '))
        if item - 1  > len(inventory.vehicles):
            print('This is an invalid number')
        else:
            inventory.vehicles.remove(inventory.vehicles[item - 1])
            print ()
            print('This vehicle has been removed')
    elif userInput == '3':
        #list all the vehicles
        if len(inventory.vehicles) < 1:
            print('Sorry there are no vehicles currently in inventory')
            continue
        inventory.viewInventory()
    elif userInput == '4':
        #edit vehicle
        if len(inventory.vehicles) < 1:
            print('Sorry there are no vehicles currently in inventory')
            continue
        inventory.viewInventory()
        item = int(input('Please enter the number associated with the vehicle to be updated: '))
        if item - 1  > len(inventory.vehicles):
            print('This is an invalid number')
        else:
            automobile = Automobile()
            if automobile.addVehicle() == True :
                inventory.vehicles.remove(inventory.vehicles[item - 1])
                inventory.vehicles.insert(item - 1, automobile)
                print ()
                print('This vehicle has been updated')
    elif userInput == '5':
        #export inventory to file
        if len(inventory.vehicles) < 1:
            print('Sorry there are no vehicles currently in inventory')
            continue
        f = open('vehicle_inventory.txt', 'w')
        f.write('\t'.join(['Make', 'Model','Year', 'Color', 'Mileage']))
        f.write('\n')
        for vechicle in inventory.vehicles:
            f.write('%s\n' %vechicle)
        f.close()
        print('The vehicle inventory has been exported to a file')
    elif userInput == '6':
        #exit the loop
        print('Goodbye')
        break
    else:
        print('invalid')

错误

Traceback (most recent call last):
  File "C:/Users/HP/PycharmProjects/tensprojectsb/vehicle.py", line 53, in <module>
    inventory.addVehicle()
  File "C:/Users/HP/PycharmProjects/tensprojectsb/vehicle.py", line 31, in addVehicle
    self.vehicles.append(vehicle)
AttributeError: 'Inventory' object has no attribute 'vehicles'

标签: pythonpython-3.x

解决方案


Python 中的各种“神奇”方法在每个名称的开头和结尾都用两个下划线拼写,而不是一个,所以应该是def __init__(...), def __str__(...),而不是def _init_(...)and def _str_(...)

作为附加提示,传递参数以__init__初始化对象,并创建addVehicle一个方法以提供交互式“构造函数”。

class Automobile:
    def __init__(self, make, model, year, color, mileage=0):
        self._make = make
        self._model = model
        self._year = year
        self._color = color
        self._mileage = mileage

    @classmethod
    def make_vehicle(cls):
        make = input('Enter vehicle make: ')
        model = input('Enter vehicle model: ')
        while True:
            year = input('Enter vehicle year: ')
            try:
                year = int(year)
                break
            except ValueError:
                print("Year must be an integer", file=sys.stderr)
        color = input('Enter vehicle color: ')

        while True:
            mileage = input('Enter vehicle mileage: ')
            try:
                mileage = int(mileage)
                break
            except ValueError:
                print("Mileage must be an integer", file=sys.stderr)


        return cls(make, model, year, color, mileage)

    def __str__(self):
        return '\t'.join(str(x) for x in [self._make, self._model, self._year, self._color, self._mileage])

此外,库存不是一种汽车。这里不应该使用继承。

class Inventory:
    def __init__(self):
        self.vehicles = []

    def add_vehicle(self):

        vehicle = Automobile.make_vehicle()
        self.vehicles.append(vehicle)

    def view(self):
        print('\t'.join(['','Make', 'Model','Year', 'Color', 'Mileage']))
        for idx, vehicle in enumerate(self.vehicles, start=1):
            print(f'{idx}\t{vehicle})

推荐阅读