2015-10-08 56 views
0

嘿,我有兩個錯誤,當我輸入飲料,並輸入糖的數量我得到「builtins.TypeError:'str'對象不可調用」,當我輸入AlcoholicDrink和金額的糖和酒精我得到「builtins.TypeError:無法將'float'對象隱式轉換爲str」。我仍然學習編碼,所以我不擅長錯誤任何幫助表示讚賞!不知道如何解決builtin.TypeError的

class Drink: 
    def __init__(self, sugar): 
     self.sugar = sugar 

    def numberOfCalories(self): 
     return 3.87 * sugar 

class AlcoholicDrink(Drink): 
    def __init__(self, alcohol, sugar): 
     super().__init__(sugar)  
     self.alcohol = alcohol 

    def numberOfCalories(self): 
     if self.alcohol > 0: 
      return self.alcohol * 7.0 + self.sugar 
     else: 
      super().numberOfCalories() 

choice = input('What would you like to drink?(Drink or AlcoholicDrink) ') 

if (choice == 'AlcoholicDrink'): 

    sugar = float(input('How much sugar is in your drink? ')) 
    alcohol = float(input('How much alcohol is in your drink? ')) 
    userDrink = AlcoholicDrink(sugar, alcohol) 

elif (choice == 'Drink'): 

    sugar = float(input('how much sugar is in your drink? ')) 
    userDrink = Drink(sugar) 

print ('Your amount of calories are ' + (userDrink.numberOfCalories())) 

回答

2

對於'str' object is not callable錯誤:你有class Drink,然後分配Drink = input(...)。後者覆蓋前者。 Python對函數,類和字符串沒有單獨的桶。使用唯一的變量名稱來避免這個問題。

對於Can't convert 'float' object to str implicitly錯誤:最後print()呼叫試圖來連接(與+)一個str'Your amount of calories are ',具有floatuserDrink.numberOfCalories()。您有這幾個選項:

轉換的floatstr

print('Your amount of calories are ' + str(userDrink.numberOfCalories())) 

多個參數傳遞給print()電話:

print('Your amount of calories are', userDrink.numberOfCalories()) 

使用字符串格式化:

print('Your amount of calories are {}'.format(userDrink.numberOfCalories())) 

使用舊字符串格式(不推薦d,因爲它有利於新的字符串格式化的棄用以上):

print('Your amount of calories are %f' % userDrink.numberOfCalories()) 
+0

@bradmonster - 對不起,我沒有注意到你提到的其他錯誤。我已經爲此添加了修復程序。 – TigerhawkT3

0

你用同名的局部變量隱藏了Drink類。使該行

Drink = input('What would you like to drink?(Drink or AlcoholicDrink) ') 

choice = input('What would you like to drink?(Drink or AlcoholicDrink) ') 

,並相應地改變所有其它參考文獻:

if (choice == 'AlcoholicDrink'): 

    sugar = float(input('How much sugar is in your drink? ')) 
    alcohol = float(input('How much alcohol is in your drink? ')) 
    userDrink = AlcoholicDrink(sugar, alcohol) 

elif (choice == 'Drink'): 

    sugar = float(input('how much sugar is in your drink? ')) 
    userDrink = Drink(sugar) 

print ('Your amount of calories are ' + (userDrink.numberOfCalories())) 
+0

我已經申請您的建議,但同樣的錯誤仍然來了。 – Brad

+0

請參閱幫助/ mcve頁面。除其他外,發佈當前代碼和完整的錯誤消息。 – Prune

0

小心,你的「喝」變量實際上是引用您之前創建的類飲料。常規變量以小寫字母開頭,類別以大寫字母開頭。採用這些約定可以幫助您避免將來出現類似問題。

將此更改爲其他名稱將有助於解決您的問題!

閱讀更多蟒蛇約定:

Proper Python Conventions

+0

我確實應用了上面可見的更改,但仍完全相同的錯誤 – Brad

相關問題