2
votes

I'm trying to create a nutrition calculator and I'm having a bit of issues regarding init().

    def main():
        print "Welcome to the MACRONUTRIENT CALCULATOR"
        User_nutrition = get_data()     
        User_nutrition.calorie_budget()


    class get_data(object):
        def __init__(self, calorie_deficit):
            self.calorie_deficit = calorie_deficit
        def calorie_bugdet(self):                                   # ask for calorie deficit
            self.calorie_deficit = float(input("Enter you calorie deficit: "))



    if __name__ == "__main__":
        main()

I get an error:

           TypeError: __init__() takes exactly 2 arguments (1 given)

However, when I look at a documentation example I see that

    class Complex:
        def __init__(self, realpart, imagpart):
           self.r = realpart
           self.i = imagpart

Is fine! I'm a bit confused. I know that init(self) sort of helps initializes the object and allocates space for it in memory but ahat is all that I know about it. Am I missing any other information about init and self that I should know about?

2

2 Answers

9
votes

The problem is with:

User_nutrition = get_data()   # one argument self
# and
def __init__(self, calorie_deficit): # two arguments

You should do

User_nutrition = get_data(5) # add one argument
# or
def __init__(self, calorie_deficit = 0): # make one argument default
6
votes

Firstly, __init__ doesn't allocate space for the object in memory, that is customized by __new__. The instance has already been created by the point __init__ is called. In this case, you accept two parameters:

class get_data(object):
    def __init__(self, calorie_deficit):
        self.calorie_deficit = calorie_deficit

The first is the instance (which is implicitly passed), so the only argument you need to pass is calorie_deficit. However in your main() call:

User_nutrition = get_data()

You don't pass that argument, so only the instance has been passed. Hence the error:

TypeError: __init__() takes exactly 2 arguments (1 given)