簡體   English   中英

如何編寫代碼以創建多個函數但我不必一次又一次地編寫相同的代碼?

[英]How can I write the code in such a way that multiple functions get created but I don't have to write the same code again and again?

我有所有這些功能做類似的任務。 我如何編寫代碼以創建所有這些函數但我不必一次又一次地編寫相同的代碼?

def get_civilservice_result(user_skill_string): 
    civilservice_keyword = firestore.client().collection('keyword').document('civilservice').get().to_dict()['key']
    civilservice_keyword_string = ' '.join(str(e) for e in civilservice_keyword)
    result = get_result(user_skill_string, civilservice_keyword_string)
    return result


def get_education_result(user_skill_string): 
    education_keyword = firestore.client().collection('keyword').document('education').get().to_dict()['key']
    education_keyword_string = ' '.join(str(e) for e in education_keyword)
    result = get_result(user_skill_string, education_keyword_string)
    return result

    
def get_engineering_result(user_skill_string): 
    engineering_keyword = firestore.client().collection('keyword').document('engineering').get().to_dict()['key']
    engineering_keyword_string = ' '.join(str(e) for e in engineering_keyword)
    result = get_result(user_skill_string, engineering_keyword_string)
    return result

您可以使用更多輸入變量來更改 function 根據其輸入所做的事情。 像這樣:

def get_result_(user_skill_string, document_type: str): 
    engineering_keyword = firestore.client().collection('keyword').document(document_type).get().to_dict()['key']
    engineering_keyword_string = ' '.join(str(e) for e in engineering_keyword)
    result = get_result(user_skill_string, engineering_keyword_string)
    return result

我會為您正在使用的關鍵字列表做一個循環:

def get_skill_result(user_skill_string, skill_field): 
    
    for skill in skill_field:
        skill_keyword = firestore.client().collection('keyword').document(skill).get().to_dict()['key']
        skill_keyword_string = ' '.join(str(e) for e in skill_keyword)
        result.append(get_result(user_skill_string, skill_keyword_string))
    
    return result

fields = ["civilservice","education","engineering"]
data = get_skill_result(user_skill_string, fields)

我會提前 go 說你根本不需要這 3 個功能。

您正在執行 2 個基本操作:

  • 為特定文檔名稱創建keyword_string字符串;
  • 獲得最終結果,對於user_skill_string和上面的keyword_string

好吧,看來您已經在某處編碼了第二個 function get_result 你只需要一個get_keyword_string

def get_keyword_string(document_name): 
    keyword = firestore.client().collection('keyword').document(document_name).get().to_dict()['key']
    return ' '.join(str(e) for e in engineering_keyword)

這就對了!

現在,在您想要調用get_civilservice_result的調用站點中,您只需要這樣做:

get_result(user_skill_string, get_keyword_string('civilservice'))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM