变量与函数

2024-10-02 20:36:20 发布

您现在位置:Python中文网/ 问答频道 /正文

嘿,有没有可能调用一个函数值而不是调用整个函数?因为,如果我调用整个函数,它将不必要地运行,这是我不想要的。 例如:

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没有定义。有没有办法存储函数的值并调用它而不是调用整个函数?在


Tags: the函数forvaluemaindeflinestart
3条回答

你可以使用“记忆化”来缓存基于函数参数的函数结果,因为你可以编写一个修饰符,这样你就可以修饰任何你认为需要这种行为的函数,但是如果你的问题和你的代码一样简单,为什么不给它赋一个变量,并用它赋值呢?在

例如

x0 = int(start_point_x_1())
a  = int(end_point_x_2()) - x0 

改变

start_point_x_1()

^{pr2}$

同样地,做

x2 = end_point_x_2()

最后:

first_calculated_point()

变成

first_calculated_point(x0, x2)

函数的定义改为:

def first_calculated_point(x0, x2):
    a  = int(x2) - int(x0)
    lamda_0 = 0
    x = x0 + (lamda_0)*a

main()

这是你想要的吗?这个想法是,你需要保存从用户那里获得的值,然后将它们传递给执行计算的函数。在

如果这不是您想要的,您需要对自己进行更多的解释(良好的缩进将有所帮助,特别是因为缩进在Python中非常重要!)。在

你为什么要同时从main和{}调用start_point_x_1和{}?在

您可以更改main的定义

def main():
  first_calculated_point()

first_calculated_point

^{pr2}$

请注意,在对a的赋值中,我将int(start_point_x_1())替换为上一行中相同表达式分配给的变量,但只有当表达式没有副作用时,才能安全地执行此操作,例如打印到屏幕或读取用户的输入。在

相关问题 更多 >