所以当我给程序时,我得到以下命令:
a = Drink(5)
b = AlcoholicDrink(4)
a. numberOfCalories
19.35
b.numberOfCalories
这是我收到错误的地方
'AlcoholicDrink' object has no attribute 'sugar'
我试过在AlcoholicDrink类中加入糖属性但是仍然有任何想法出现同样的错误?
class Drink:
def __init__(self,sugar,drink = 0):
self.sugar = sugar
self.drink = drink
def numberOfCalories(self):
return self.sugar * 3.87
class AlcoholicDrink(Drink):
def __init__(self,alcohol):
self.alcohol = alcohol
def numberOfCalories(self):
if self.alcohol > 0:
self.alcohol * 7.0 + self.sugar
else:
super.numberOfCalories()
答案 0 :(得分:4)
您需要在.__init__()
__init__
中致电super()
AlcoholicDrink
。如果你不这样做,Drink.__init__
中的内容就不会运行。
您还应在sugar
的构造函数中添加drink
和AlcoholicDrink
的参数,并将其传递给super().__init__
。这是一个例子:
class Drink:
def __init__(self, sugar, drink=0):
self.sugar = sugar
self.drink = drink
def number_of_calories(self):
return self.sugar * 3.87
class AlcoholicDrink(Drink):
def __init__(self, alcohol, sugar, drink=0):
super().__init__(sugar, drink)
self.alcohol = alcohol
def number_of_calories(self):
if self.alcohol > 0:
return self.alcohol * 7.0 + self.sugar
else:
return super().number_of_calories()
我修复了您的代码的其他几个问题:
AlcoholicDrink.number_of_calories
没有返回任何内容。super
AlcoholicDrink.number_of_calories
之后丢失了一些parens