Python式的? ...动态调用嵌套函数
这是一个Pythonic实现吗?
我使用包装器从字符串参数动态调用嵌套函数,以减少调用不存在函数的机会。这是一个示例,我想对 arg1 和 arg2 执行不同的比较(按照 ==、>=、< 等)...
class ComparisonClass(object):
def__init__(self):
pass
def comparison(self,arg1,arg2,comparison):
def equal_to():
pass
def greater_than():
pass
def less_than():
pass
return locals()[comparison]()
def comparison_equal_to(self,arg1,arg2):
return self.comparison(arg1,arg2,'equal_to')
def comparison_greater_than(self,arg1,arg2):
return self.comparison(arg1,arg2,'greater_than')
def comparison_less_than(self,arg1,arg2):
return self.comparison(arg1,arg2,'less_than')
Is this a a pythonic implementation?
I'm calling nested functions dynamically from a string argument with wrappers to reduce the chance of calling a non-existent function. Here's an example where I want to perform different comparisons on arg1 and arg2 (in terms of ==, >=, < etc)...
class ComparisonClass(object):
def__init__(self):
pass
def comparison(self,arg1,arg2,comparison):
def equal_to():
pass
def greater_than():
pass
def less_than():
pass
return locals()[comparison]()
def comparison_equal_to(self,arg1,arg2):
return self.comparison(arg1,arg2,'equal_to')
def comparison_greater_than(self,arg1,arg2):
return self.comparison(arg1,arg2,'greater_than')
def comparison_less_than(self,arg1,arg2):
return self.comparison(arg1,arg2,'less_than')
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
实现在这里是无关紧要的,因为您寻求实现的东西并不是 Pythonic 的。
在Python中,我们使用
__eq__
系列方法进行比较,并且标准库中存在用于根据其他方法实现其中一些方法的工具。Implementation is irrelevant here because the very thing you seek to implement isn't Pythonic.
In Python, we use the
__eq__
family of methods for comparisons, and there exist tools in the standard library for implementing some of them in terms of others.你缺少的是,在 Python 中,函数是一等对象。这意味着它们可以被分配给变量并像任何其他对象一样传递。
因此,您不需要嵌套函数并在父函数中调用它,而只需将相关函数指定为函数的返回值,并在返回时调用它。或者更好的是,在类级别分配一个包含函数的字典:
现在您可以调用
COMPARISONS['equal_to'](arg1, arg2)
。What you're missing is that in Python, functions are first-class objects. That means they can be assigned to variables and passed around just like any other object.
So, rather than nesting a function and calling it within the parent function, you just want to assign the relevant function as the return value of your function, and call it on return. Or even better, assign a dictionary at class level containing the functions:
Now you can call
COMPARISONS['equal_to'](arg1, arg2)
.