__init__() 的类型错误 [英] TypeError for __init__()

查看:115
本文介绍了__init__() 的类型错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个营养计算器,但在 init() 方面遇到了一些问题.

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

我收到一个错误:

           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

没问题!我有点困惑.我知道 init(self) 有助于初始化对象并在内存中为它分配空间,但我所知道的仅此而已.我是否遗漏了我应该了解的关于 init 和 self 的任何其他信息?

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?

推荐答案

问题在于:

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

你应该这样做

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

这篇关于__init__() 的类型错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆