2017-10-21 114 views
1

更具體地說,我想從 calc_gross_pay中調用函數get_hours_worked。我意識到另一種做法是將參數傳遞給calc_gross_pay,但是我想知道我想要做什麼是可能的。我有一種感覺,它不是。謝謝你的幫助。調用另一個函數內部的函數

def main(): 
# 
    print("This employee's gross pay for two weeks is:",calc_gross_pay()) 


def get_input(): 

    def get_hours_worked(): 
     #get_hours_worked 
     x = float(input("How many hours worked in this two week period?  ")) 
     return x 

    def get_hourly_rate(): 
     #get_hourly_rate() 

     y = float(input("What is the hourly pay rate for this employee? ")) 
     return y 

def calc_gross_pay(): 
    # 
    gross = get_input(get_hours_worked) * get_input(get_hourly_rate) 
    return gross 

main() 
+0

在函數中聲明函數的任何特定原因? – ZdaR

+1

不,名稱'get_hours_worked'和'get_hourly_rate'是'get_input'的本地名稱。如果你想訪問'get_input'之外的那些函數,你需要返回它們。但是,爲什麼你要在'get_input'裏面定義這些函數呢? –

+0

只需調用'get_hours_worked()'完成工作時,爲什麼要調用'get_input(get_hours_worked)'?在你的例子中'get_input'什麼都不做。 – mshsayem

回答

1

這是您的代碼的重組版本。我們將其定義爲get_input內部的get_hours_workedget_hourly_rate,我們將它們定義爲單獨的函數,這些函數稱爲get_input

def get_input(prompt): 
    return float(input(prompt)) 

def get_hours_worked(): 
    return get_input("How many hours worked in this two week period? ") 

def get_hourly_rate(): 
    return get_input("What is the hourly pay rate for this employee? ") 

def calc_gross_pay(): 
    return get_hours_worked() * get_hourly_rate() 

def main(): 
    print("This employee's gross pay for two weeks is:", calc_gross_pay()) 

main() 

演示

How many hours worked in this two week period? 50 
What is the hourly pay rate for this employee? 20.00 
This employee's gross pay for two weeks is: 1000.0 
+0

謝謝,這樣做更有意義,我誤解了我的文本中的層次結構圖表 –

0

由於PM 2Ring指出的那樣,它能夠更好地更改層級本身。但如果你仍然想要,請按照以下步驟操作:

def get_input(): 

    def get_hours_worked(): 
     x = float(input("How many hours worked in this two week period?  ")) 
     return x 

    def get_hourly_rate(): 
     y = float(input("What is the hourly pay rate for this employee? ")) 
     return y 

    return get_hours_worked, get_hourly_rate       # IMP 

def calc_gross_pay(): 
    call_worked, call_rate = get_input()        # get the functions 
    gross = call_worked() * call_rate()        # call them 
    return gross  


def main(): 
    print("This employee's gross pay for two weeks is:",calc_gross_pay()) 

    #How many hours worked in this two week period? 3 
    #What is the hourly pay rate for this employee? 4 
    #This employee's gross pay for two weeks is: 12.0 

main() 
+0

哦,哇這將起作用嗎?所以當你說call_worked時,你的意思是get_hours_worked?我只是確保「call」不是關鍵字,然後使用賦值運算符和get_input(),這很奇怪,「=」仍然表現爲賦值運算符嗎? 編輯:現在我已經走得更近了看起來,call_worked似乎是一個局部變量BLE。由於有兩個變量call_worked和call_rate,它們從get_input接收返回的值。我猜他們會按照返回的順序收到返回的日期? –

+0

是的,你的第二個猜測(編輯部分)達到了這一點。來自'get_input'的返回值是兩個函數,它們被分配給兩個變量'call_worked'和'call_rate'。使用我們訪問的功能。 –

相關問題