0

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()
3
  • where did you add the sugar attribute? Commented Oct 2, 2015 at 14:33
  • 1
    As you're coming from a Java/C# background, one difference is the base constructor doesn't automatically run if you override it in a derived class. Commented Oct 2, 2015 at 14:37
  • What @PeterWood said. Although to be accurate __init__ is the instance initializer, the constructor is __new__; your classes are using the __new__ method of the parent object class, since they don't override __new__ (and there's rarely a need to do so). Commented Oct 2, 2015 at 14:55

1 Answer 1

4

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:

Sign up to request clarification or add additional context in comments.

8 Comments

I don't understand? Can you change the line and show me what it should look like?
@bradmonster I added a working example, let me know if that helps, or if you still have any questions.
Hey, for a = drink(4) and a.numberOfCalories this part works, but when type b = AlcoholicDrink(4) I get this error "__init__() missing 1 required positional argument: 'sugar'"
@bradmonster Well, yeah. You need to either give sugar a default value or provide it when you create an instance of the class.
Thank you so much! Much help!
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.