python - Python:使用的不同方法
问题描述
请协助使用以下代码。我真的很挣扎。
定义一个具有两个成员变量 style 和 price 的类 Shoe。变量 style 存储值“A”、“B”或“O”,而 price 存储鞋子的原始价格。
添加以下方法:
- 该类的 init() 方法将样式设置为空字符串并将价格设置为 0.0。p111,-114
- 一个名为 assignValues 的方法,它将为 Shoe 类实例的成员变量赋值。
- 一个名为 calcDiscountPrice() 的方法,它将计算折扣价并将折扣价返回给主程序。折扣计算如下:
- 款式 A – 原价的 10%
- 款式 B – 原价的 20%
- 对于风格 O - 无折扣
- 一个名为 dispValues() 的方法,它将显示 Shoe 实例的成员变量。
编写一个程序,将 Shoe 类的实例存储在二进制文件中并对其进行处理。在文件中至少存储三个实例。主程序应尝试如下:
- 创建类 Shoe 的实例。
- 要求用户输入实例的详细信息(价格和样式)。
- 将实例添加到文件中。
- 向用户显示一个提示——“你想继续吗(y/n)”
- 程序应该反复询问实例的详细信息,直到用户在提示下拒绝。
- 用户完成向文件添加实例后,读取文件并显示文件内容。对于每个实例,还显示折扣价。
示例运行:
输入鞋子款式('A', 'B' or 'O'):O 输入鞋子价格:R299.99 输入鞋款('A', 'B' or 'O'):A 输入鞋子价格:R349.50
折扣价文件中每个 Shoe 实例的详细信息如下:
鞋实例1 鞋型:O 价格:R299.99 折扣价为 R299.99 鞋实例2 鞋型:A 价格:R349.50 折扣价为 R314.55
我的代码:
class shoe:
style=""
price=0.0
def _init_(self,style=" ",price=0.0,discountP=0.0):
self.style=" "
self.price=0.0
self.discountP=0.0
def assignValues(self):
self.style=str(input("Enter a shoe style('A','B' or 'O'): "))
self.price=float(input("Enter price of the shoe: "))
while True:
word=str(input("Do you want to continue? (y/n): "))
if word=="n":
break
else:
self.style=str(input("Enter a shoe style('A', 'B' or 'O'): "))
self.price=float(input("Enter the shoe style: "))
def calcDiscountPrice(self):
if self.style =="A":
self.discountP=self.price-(self.price*0.1)
if self.style =="B":
self.discountP=self.price-(self.price*0.2)
if self.style =="C":
self.discountP=self.price
def displayValues(self):
print("\n\n The details of each shoe instance in the file with discount")
print("Shoe style: ", self.style)
print("Price: R", % self.price)
print("Discounted price is R", self.disountP))
s=shoe()
f=open("ShoeDetails.bin","w")
s.assignValues()
s.calcDiscountPrice()
s.dispValues()
pickle.dump(s, file)
file.write(s)
file.close()
del r
f=open("ShoeDetails.bin","r")
storedobj = pickle.load(f)
print(storedobj.dispValues())
解决方案
换行
f=open("ShoeDetails.bin","w")
到
f=open("ShoeDetails.bin","wb")
注意w
和wb
。当写入二进制模式的 bin 文件时,您需要使用wb
(write binary) 选项。
推荐阅读
- mysql - 创建映射并在 MySQL 存储过程中使用它
- audio - FFmpeg 删除具有通过检测静默检测到的确切持续时间的静默
- prolog - 如何在 alpha-beta 算法中返回下一步?
- tensorflow - 如何在 tensorflow js 转换器中获取单个权重文件
- ios - 将 Bugsnag 与共享扩展一起使用
- ios - 为什么以前从堆栈中弹出的视图仍然处于活动状态
- javascript - ${this...} 在 Node v13.14 中不显示值
- python - Python netcdf cartopy - 绘制数据选择
- php - POST http://localhost:8000/offers-ajax/store 419 (未知状态) Laravel AJAX
- python - ModuleNotFoundError:没有名为“maraboupy.MarabouCore”的模块