获取对象具有属性错误

时间:2015-10-02 14:29:21

标签: python attributes

所以当我给程序时,我得到以下命令:

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()

1 个答案:

答案 0 :(得分:4)

您需要在.__init__() __init__中致电super() AlcoholicDrink。如果你不这样做,Drink.__init__中的内容就不会运行。

您还应在sugar的构造函数中添加drinkAlcoholicDrink的参数,并将其传递给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()

我修复了您的代码的其他几个问题: