1

我在python中有以下代码:

class TotalCost:
      #constructor
      def __init__(self, quantity, size):
       self.__quantity=quantity
       self.__size=size
       self.__cost=0.0
       self.__total=0.0
      def DetermineCost(self):
        #determine cost per unit
       if self.__size=="A":
           self.__cost=2.29
       elif self.__size=="B":
           self.__cost=3.50
       elif self.__size=="C":
           self.__cost=4.95
       elif self.__size=="D":
           self.__cost=7.00
       elif self.__size=="E":
           self.__cost=9.95
    def DetermineTotal(self): #calculate total
       self.__total= self.__cost * self.__quantity
    def GetCost(self):
       return self.__cost
      def GetTotal(self):
       return self.__total
      def Menu(self):
       print("----------------SIZES/PRICES----------------")
       print("               Size A = $2.92")
       print("               Size B = $3.50")
       print("               Size C = $4.95")
       print("               Size D = $7.00")
       print("               Size E = $9.95")
       print("--------------------------------------------")
    def main():
     again=""
     print("Prices:")
     while again!="no":
        size=""
        quantity=0
        display="" #i put this variable only because it wont go without it and idk what else to do>.<
        TotalCost.Menu(display)
        while size!="A" and size!="B" and size!="C" and size!="D" and size!="E":
            size=str(input("Which size? Please enter A,B,C,D, or E. : "))
        quantity=int(input("How many of this size? : "))
        while quantity<0:
            quantity=int(input("How many of this size? : "))
        Calc=TotalCost(size, quantity)  
        Calc.DetermineCost()
        Calc.DetermineTotal()
        print("--------------------------------------------")
        print("Your order:")
        print("Size: " , size)
        print("Quantity: " , quantity)
        print("Cost each: $" , Calc.GetCost())        print("Total cost: $", Calc.GetTotal())

    main()  

执行此代码时收到以下错误:

文件“C:/Python33/halpmeanon.py”,第 21 行,DetermineTotal self._total =self。_cost * self.__quantity TypeError:不能将序列乘以“浮点”类型的非整数

语境

这个程序应该要求一个字母(尺寸)和数量,通过给定的字母确定每单位的成本,并计算/输出总成本。

如何解决我的代码中的这个错误?

4

1 回答 1

4

您以错误的方式获得了参数的顺序

Calc=TotalCost(size, quantity)  

你的构造函数是:

  def __init__(self, quantity, size):

一种很好的编码方法是在调用方法时为参数命名,这样您就可以确保不会发生这种情况:

代替:

Calc=TotalCost(size, quantity)

做这个:

Calc=TotalCost(size=size, quantity=quantity) # or TotalCost(quantity=quantity, size=size)

这样你就可以乱序地给出参数,而不必担心像你遇到的那样的错误。

于 2013-05-09T18:21:00.543 回答