python - __init__() 的类型错误

标签 python python-2.7

我正在尝试创建一个营养计算器,但我遇到了一些关于 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)

但是,当我查看文档示例时,我看到了

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

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

最佳答案

问题在于:

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

关于python - __init__() 的类型错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16835651/

相关文章:

python - Python 的 ftplib 的替代品?

Python 将元组值从 unicode 转换为 str

python - python 中的并行性无法正常工作

python-2.7 - 匹配模式的列表理解

python - 全新安装时导入 ssl 错误 : 'PROTOCOL_TLS' is not defined

python - 正则表达式查找时间戳后的最后一个冒号

python - 向 Eclipse 控制台中运行的程序发送 SIGINT (Ctrl-C)

python没有名为serial的模块

python - 使用正则表达式查找函数调用

python - Python 如何知道变量的数据类型?