Home > Software engineering >  How can I pass a function and its arguments to an object at the moment of instantiation in Python?
How can I pass a function and its arguments to an object at the moment of instantiation in Python?

Time:04-28

Consider the class below:

class Test():
  def __init__(self, data, transformation = None):
    self.data = data
    self.transformation = transformation

  def my_method(self):
    if self.transformation:
      data = self.transformation(self.data)
    return data

This class gets a data and a function as its arguments which will perform some transformation on the data. Now, outside of the class I make a function to perform the transformations I want. However, the function I define, takes several arguments besides the data itself. How can I pass those extra parameters to the class at the moment I am making an object in the code below?

instance = Test(data, my_func)

CodePudding user response:

You can partially apply the arguments:

import functools

def my_func(a, b, c):
    return a * b   c

class Test():
  def __init__(self, data, transformation = None):
    self.data = data
    self.transformation = transformation

  def my_method(self):
    if self.transformation:
      data = self.transformation(self.data)
    return data

instance = Test(2, functools.partial(my_func, 3, 4))
print(instance.my_method()) # prints 14 (3 * 4   2)

functools.partial is a higher order function in the standard library that takes a function, some of its arguments, and returns a new function that takes the rest and then calls the original function.

  • Related