user5327466
user5327466

Reputation:

Getting a object has attribute error

So when I give the program the follow commands I get:

a = Drink(5)

b = AlcoholicDrink(4)

a. numberOfCalories

19.35

b.numberOfCalories

This is where I get the error

'AlcoholicDrink' object has  no attribute 'sugar'

I have tried adding in sugar attribute to the AlcoholicDrink class but still getting the same error any ideas?

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

Upvotes: 0

Views: 112

Answers (1)

Morgan Thrapp
Morgan Thrapp

Reputation: 9986

You need to call super().__init__() in the __init__ for AlcoholicDrink. If you don't, the stuff in Drink.__init__ won't run.

You should also add parameters for sugar and drink in the constructor for AlcoholicDrink and pass them to super().__init__. Here's an example:

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

You had a couple other issues with your code that I fixed:

Upvotes: 4

Related Questions