首页 > 解决方案 > Python:使用的不同方法

问题描述

请协助使用以下代码。我真的很挣扎。

定义一个具有两个成员变量 style 和 price 的类 Shoe。变量 style 存储值“A”、“B”或“O”,而 price 存储鞋子的原始价格。

添加以下方法:

编写一个程序,将 Shoe 类的实例存储在二进制文件中并对其进行处理。在文件中至少存储三个实例。主程序应尝试如下:

示例运行:

输入鞋子款式('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())

标签: python

解决方案


换行

f=open("ShoeDetails.bin","w")

f=open("ShoeDetails.bin","wb")

注意wwb。当写入二进制模式的 bin 文件时,您需要使用wb(write binary) 选项。


推荐阅读