2016-08-20 60 views
0

我對Python和編程完全陌生,但我正在嘗試使用更實用的方法來學習它。如何創建包含函數名稱的列表?

我想要做的是練習轉換不同的單位,例如,磅 - >公斤,腳 - >米等

我已經定義的所有功能,針對不同單位對:

def kg_to_g(value):  
    return round(value*1000.0,2) 
def g_to_kg(value):  
    return round(value/1000.0,2) 
def inch_to_cm(value): 
    return round(value*2.54,2) 
def cm_to_inch(value): 
    return round(value/2.54,2) 
def ft_to_cm(value):  
    return round(value*30.48,2) 

,並創建了一個清單,這些函數名稱:

unit_list = ['kg_to_g','g_to_kg','inch_to_cm','cm_to_inch', 
     'ft_to_cm','cm_to_ft','yard_to_m','m_to_yard', 
     'mile_to_km','km_to_mile','oz_to_g','g_to_oz', 
     'pound_to_kg','kg_to_pound','stone_to_kg','kg_to_stone', 
     'pint_to_l','l_to_pint','quart_to_l','l_to_quart', 
     'gal_to_l','l_to_gal','bar_to_l','l_to_bar'] 

程序應該隨機選擇一個單元對(例如公斤─>磅)和值(例如134.23),並且用戶將被要求的那些值進行轉換。

random_unit = random.choice(unit_list) 
lower = 0.1001 
upper = 2000.1001 
range_width = upper - lower 
ranval = round(random.random() * range_width + lower, 2) 

當用戶輸入答案,程序應該比較答案與函數定義的計算,並告訴用戶,如果它是一個正確的答案或錯誤的答案:

def input_handler(answer): 
    if answer == random_unit(ranval): 
     label2.set_text("Correct!") 
    else: 
     label2.set_text("Wrong!") 

不幸的是,這樣的程序沒有按」將不起作用,並且codesculptor(codesculptor.org)與返回錯誤

TypeError: 'str' object is not callable 

可能有人請向我解釋什麼是錯的代碼,並提出一些解決日問題。

+1

在'random_unit = random.choice(unit_list)'後面加上'random_unit = globals()[random_unit]'。 –

+0

'random_unit = random.choice(unit_list)':這一行將隨機指定一個'unit_list'(這是一個'str'列表)到'random_unit'。然後你調用'random_unit(ranval)',所以你使用'str'就像一個函數(可調用函數是函數的另一個名稱)。 – kjaquier

回答

0

因爲您已將函數名(在列表中)括在引號中,所以它們變成了字符串。

列表更改爲:

unit_list = [kg_to_g, g_to_kg, inch_to_cm, cm_to_inch, 
     ft_to_cm, cm_to_ft, yard_to_m, m_to_yard, 
     mile_to_km, km_to_mile, oz_to_g, g_to_oz, 
     pound_to_kg, kg_to_pound, stone_to_kg, kg_to_stone, 
     pint_to_l, l_to_pint, quart_to_l, l_to_quart, 
     gal_to_l, l_to_gal, bar_to_l, l_to_bar] 

,現在它的功能,它可以被稱爲像這樣的列表:unit_list[0](34),例如。

所以現在random_unit(ranval)不應該拋出異常。

請注意,比較花車(if answer == random_unit(ranval))很可能會導致您的問題。請參閱Is floating point math broken?瞭解爲什麼這是一些詳細的解釋。

當你四捨五入時,你可能會忽略它,但很好意識到這一點,並理解你需要在代碼中處理它。

+0

'getattr'在這裏不需要? – Ejaz

+0

@PEJK不,如果函數在列表中被硬編碼,就像這樣。如果你在一個變量中有一個函數的名字並且想要調用它,那麼是的,'getattr()'是你的朋友,但這裏沒有必要。當定義列表時,元素是對函數本身的引用。 – SiHa

+0

這個解決方案適合我!謝謝!我的錯在於,我在創建單元對列表後定義了單元對函數 - 導致錯誤,指出函數未定義。 –

-1

我認爲這是你問的問題。你應該能夠存儲的功能列表中的這樣

unit_list = [kg_to_g, g_to_kg, inch_to_cm, cm_to_inch, ft_to_cm] 

然後可以調用列表中的每個項目,並給它一個參數,它應該執行的功能,例如像這樣:

unit_list[0](value) 
相關問題