嘿,有没有可能调用一个函数值而不是调用整个函数?因为,如果我调用整个函数,它将不必要地运行,这是我不想要的。 例如:
def main():
# Inputing the x-value for the first start point of the line
start_point_x_1()
# Inputing the x-value for the 2nd end point of the line
end_point_x_2()
# The first output point calculated and printed
first_calculated_point()
def start_point_x_1():
return raw_input("Enter the x- value for the 1st " +
"start point for the line.\n")
def end_point_x_2():
return raw_input("Enter the x- value for the 2nd " +
"end point for the line.\n")
def first_calculated_point():
x0 = int(start_point_x_1())
a = int(end_point_x_2()) - int(start_point_x_1())
lamda_0 = 0
x = x0 + (lamda_0)*a
main()
上面的代码可以工作,但是当我到达函数first_calculated_point
并计算x0
时,函数{start_point_x_1()
下存储函数{x0 = x1
调用变量{x1
没有定义。有没有办法存储函数的值并调用它而不是调用整个函数?在
你可以使用“记忆化”来缓存基于函数参数的函数结果,因为你可以编写一个修饰符,这样你就可以修饰任何你认为需要这种行为的函数,但是如果你的问题和你的代码一样简单,为什么不给它赋一个变量,并用它赋值呢?在
例如
改变
到
^{pr2}$同样地,做
最后:
变成
函数的定义改为:
这是你想要的吗?这个想法是,你需要保存从用户那里获得的值,然后将它们传递给执行计算的函数。在
如果这不是您想要的,您需要对自己进行更多的解释(良好的缩进将有所帮助,特别是因为缩进在Python中非常重要!)。在
你为什么要同时从}调用}?在
main
和{start_point_x_1
和{您可以更改
main
的定义和
^{pr2}$first_calculated_point
:请注意,在对
a
的赋值中,我将int(start_point_x_1())
替换为上一行中相同表达式分配给的变量,但只有当表达式没有副作用时,才能安全地执行此操作,例如打印到屏幕或读取用户的输入。在相关问题 更多 >
编程相关推荐