python - 定义类函数的好方法,这些函数都调用具有不同参数的相同函数
问题描述
我正在编写一个具有一堆成员函数的类,这些函数都使用不同的参数调用相同的函数。我现在写的方式是这样的:
class ExampleClass:
def a_function(self,args):
do_something
def func1(self):
return self.a_function(arg1)
def func2(self):
return self.a_function(arg2)
.
.
.
这似乎是多余的,而且处理起来很痛苦,因为它占用了太多空间。这是处理所有具有相同结构的类函数的最佳方法还是有更好的方法来处理这个问题?
解决方案
由于函数是 Python 中的第一类对象,因此您可以在另一个内部创建和返回一个。这意味着您可以定义一个辅助函数并在类中使用它来摆脱一些样板代码:
class ExampleClass:
def a_function(self, *args):
print('do_something to {}'.format(args[0]))
def _call_a_function(arg):
def func(self):
return self.a_function(arg)
return func
func1 = _call_a_function(1)
func2 = _call_a_function(2)
func3 = _call_a_function(3)
if __name__ == '__main__':
example = ExampleClass()
example.func1() # -> do_something to 1
example.func2() # -> do_something to 2
example.func3() # -> do_something to 3
如果您使用的是相当新的 Python 版本,您甚至不必编写辅助函数,因为有一个名为 的内置函数partialmethod
:
from functools import partialmethod # Requires Python 3.4+
class ExampleClass2:
def a_function(self, *args):
print('do_something to {}'.format(args[0]))
func1 = partialmethod(a_function, 1)
func2 = partialmethod(a_function, 2)
func3 = partialmethod(a_function, 3)
推荐阅读
- list - Maya:获取脚本创建的所有节点的名称
- php - PHP中的组和循环问题
- python - 使用绘图字典在同一图形上绘制两条线
- reactjs - Redux saga - 如果数据已存在于 redux 存储中,则跳过 API 请求
- r - 谁能帮我用 R 处理数据?[图片更新]
- css - 使用线性渐变制作 CSS 颜色
- graphql - 如何使用从 Gatsby 中的 Contentful 获取的值过滤从 Contentful 获取的数据?
- visual-studio-code - 我可以通过 CLI 使用要在集成终端上运行的命令在 VS Code 中打开文件夹吗?
- mongodb - 猫鼬链接列表如何
- rest - 将非常大的组(20k+ 成员)添加为受邀者时,Google 日历 REST API 返回 503