Reputation: 119
I'm writing a class that has a bunch of member functions that all call the same function with different parameters. The way I have it written right now is like:
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)
.
.
.
This seems incredibly redundant and is a pain to deal with since it takes up so much space. Is this the best way to deal with class functions that all have the same structure or is there a better way to deal with this?
Upvotes: 0
Views: 77
Reputation: 123453
Since functions are first class objects in Python you can create and return one inside of another. This means you could do define a helper function and use it inside the class to get rid of some of the boilerplate code:
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
If you're using a fairly recent version of Python, you don't even have to write the helper function because there's a built-in one named 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)
Upvotes: 2