定义类函数的漂亮方法,这些函数都使用不同的参数调用相同的函数



我正在编写一个类,该类具有一堆成员函数,这些成员函数都使用不同的参数调用相同的函数。我现在写它的方式是这样的:

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)

最新更新