2010-01-01 91 views
0

嘿,是不是可以調用一個函數值,而不是調用整體功能的?作爲,如果我叫整體功能,這將不必要地運行它,我不想。 例如:變量和函數

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()運行again.I試圖存儲等功能「例如x1 = raw_input("Enter the x- value for the 1st " + "start point for the line.\n")作用下start_point_x_1()但是當我所說的變量x1x0 = x1,他們說沒有定義x1。有什麼辦法來存儲函數的值,並調用它而不是調用整個函數?

+0

您的代碼不可能工作?縮進似乎是錯誤的(因爲函數定義下面沒有縮進行)。至少,您需要在那裏使用「傳遞」語句。請重新格式化代碼,使其看起來與您正在運行的程序完全相同。 – richardolsson 2010-01-01 13:04:50

+0

對不起,我忘了添加打印x – blur959 2010-01-01 13:34:27

回答

3

變化

start_point_x_1() 

x0 = start_point_x_1() 

同樣,做

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顯著!)。

0

爲什麼從mainfirst_calculated_point都撥打start_point_x_1end_point_x_2

你可以改變的main

def main(): 
    first_calculated_point() 

first_calculated_point的定義:

def first_calculated_point(): 
    x0 = int(start_point_x_1()) 
    a = int(end_point_x_2()) - x0 
    lamda_0 = 0 
    x = x0 + (lamda_0)*a 

    # did you mean to return x? 

注意的是,在分配給a,我換成int(start_point_x_1())與到被分配在同一個表達變量前行,但你可以做到這一點安全,只有當表達式不具有副作用,如打印屏幕或用戶讀取輸入。

0

您可以使用'memoization'緩存基於函數參數的函數結果,因爲您可以編寫一個裝飾器,以便您可以修飾您認爲需要該行爲的任何函數,但是如果問題與您的問題一樣簡單代碼是爲什麼不給它分配一個變量,並使用分配的值?

e。g

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

記憶是對這個問題極端矯枉過正。他只需要重新組織他的代碼。 – 2010-01-01 14:48:30