[英]python locals() redundant usage
Hi I am kinda new to using locals(), I did research that locals() means treat a variable within a function as a dictionary. 嗨,我对使用locals()有点陌生,我确实研究过locals()意味着将函数内的变量视为字典。 We have a bunch if this function with the same function of locals() below. 如果此函数与下面的locals()函数具有相同的功能,则有很多。 I am man of DRY principle but in this area its not. 我是DRY原则的人,但在这方面不是。 How will I simplify this or any alternative way? 我将如何简化此方法或任何其他替代方法?
def home_creation(self, property, item):
def date(data):
return data
def rate(data):
return data
if property in locals():
return locals()[property](item)
else:
return None
You can define your own dictionary to limit the permitted methods for use: 您可以定义自己的字典以限制允许使用的方法:
def home_creation(self, property, item):
def date(data):
return data
def rate(data):
return data
functions = {
'date': date,
'rate': rate
}
return functions.get(property, lambda: None)(item)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.