嘿,当我输入饮料并输入我得到的糖量时,我有两个错误" builtins.Type错误:' str'对象不可调用"当我输入AlcoholicDrink和糖和酒量时,我得到了#34; builtins.Type错误:无法转换'浮动'反对str含义"。我仍然学习编码,所以我对错误不满意任何帮助都表示赞赏!
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()))
答案 0 :(得分:1)
对于'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 '
,{{1} },float
。你有几个选择:
将userDrink.numberOfCalories()
转换为float
:
str
将多个参数传递给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()))
答案 1 :(得分: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()))
答案 2 :(得分:0)
请注意,您的“Drink”变量实际上是引用您之前创建的Drink类。传统上,变量以小写字母开头,类以大写字母开头。采用这些约定可以帮助您避免将来出现类似问题。
将其更改为其他名称有助于解决您的问题!
阅读本文以了解更多python约定: