首页 > 解决方案 > 定义类函数的好方法,这些函数都调用具有不同参数的相同函数

问题描述

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

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

解决方案


由于函数是 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)

推荐阅读