我正在尝试创建一个营养计算器,我有一些关于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()
Run Code Online (Sandbox Code Playgroud)
我收到一个错误:
TypeError: __init__() takes exactly 2 arguments (1 given)
Run Code Online (Sandbox Code Playgroud)
但是,当我查看文档示例时,我看到了这一点
class Complex:
def __init__(self, realpart, imagpart):
self.r = realpart
self.i = imagpart
Run Code Online (Sandbox Code Playgroud)
很好!我有点困惑.我知道init(self)有助于初始化对象并在内存中为它分配空间,但这就是我所知道的.我是否遗漏了关于init和self的其他任何我应该知道的信息?
问题在于:
User_nutrition = get_data() # one argument self
# and
def __init__(self, calorie_deficit): # two arguments
Run Code Online (Sandbox Code Playgroud)
你应该做
User_nutrition = get_data(5) # add one argument
# or
def __init__(self, calorie_deficit = 0): # make one argument default
Run Code Online (Sandbox Code Playgroud)
首先,__init__
不为内存中的对象分配空间,这是由自定义的__new__
.已经通过__init__
调用点创建了实例.在这种情况下,您接受两个参数:
class get_data(object):
def __init__(self, calorie_deficit):
self.calorie_deficit = calorie_deficit
Run Code Online (Sandbox Code Playgroud)
第一个是实例(隐式传递),因此您需要传递的唯一参数是calorie_deficit
.但是在你的main()
电话中:
User_nutrition = get_data()
Run Code Online (Sandbox Code Playgroud)
您没有传递该参数,因此只传递了实例.因此错误:
TypeError: __init__() takes exactly 2 arguments (1 given)
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
818 次 |
最近记录: |