![](/img/trans.png)
[英]Can I somehow merge these classes such that I don't have to write this again and again and my python code doesn't get redundant
[英]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.