python - 在这个程序中我得到属性错误?谁能解决这个错误并向我解释
问题描述
这是一个小型汽车经销商的简单库存程序。
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'
解决方案
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})
推荐阅读
- php - 从 octobercms 中的非 ajax 表单获取输入值
- java - 在模型更改时更新虚拟 TableViewer 的条目
- jquery - 每个链接的隐藏 div 以在悬停时显示
- java - java方法可以返回不同的对象吗?
- dailymotion-api - 如何在 Dailymotion 嵌入式播放器中默认激活任何语言的字幕
- javascript - 使用节点请求将数组发送到 PHP 服务器?
- python - 让 lambda 在循环中生成唯一数据
- reactjs - 如何在 onChange 后清除 Material-ui 中的自动完成输入?
- powershell - PowerShell 导出不在特定组中的 AD 用户 + 属性
- c++ - 如何更改包含二维数组c ++的最高值和最低值的列