0

I would like to define a class such as the following FunctionCatalogue class. In this class, there is a catalogue of staticmethod. These methods can thus be used without instantiating the class. The functions are labeled from tuple of integers. I defined the __call__ special method to be able to compute the relevant function values when the class is instantiated.

In order to do the same but without instantiating the class, I would had like to define the dictionary functions as a class attribute that provides the link between the tuple of integers and the give functions. But, as expected, the this_class is not defined neither FunctionCatalogue or obviously self as the class was not yet instantiated.

I wonder if there is a way to implement this or maybe a better approach to do the same ?

class FunctionCatalogue:

    functions = {
        (0, 0): this_class.func1,
        (0, 1): this_class.func2,
    }

    def __init__(self, i, j):
        self.i = i # with tests on i values
        self.j = j # with tests on j values

    @staticmethod
    def func1(x):
        return x + 1
    
    @staticmethod
    def func2(x):
        return 2 * x + 2

    def __call__(self, x):
        return self.functions[(self.i, self.j)](x)

To be more clear, the idea is to be able to do

>>> my_f = FunctionCatalogue(0, 0)
>>> my_f(2)

or something like

>>> FunctionCatalogue.func1(2)

or

>>> FunctionCatalogue.functions[(0, 0)](2)
Ger
  • 9,076
  • 10
  • 37
  • 48
  • 1
    There almost certainly a better approach. For example, don't use a class. – mkrieger1 Feb 08 '22 at 10:35
  • Yes the answer you provided is a solution. Actually, I have just to define the staticmethod first ... About your second comment, your suggestion is for example to simply put the function outside of the class and keep only the functionality to select the function in the class ? – Ger Feb 08 '22 at 10:38
  • 1
    No, move the functionality to select the function out of the class, too. A class with an `__init__` and a `__call__` method is just a function in disguise. – mkrieger1 Feb 08 '22 at 10:38
  • 1
    This is one of the situations in which OOP doesn't solve your problem but rather adds more. Unless you have a very specific requirement that forces you to use a class, simply don't. – Shinra tensei Feb 08 '22 at 10:40
  • I think in this case, the only interest of the class is to avoid to make the tests on the values of `i` and `j` each time you call the function. But maybe I can refactor the code to do that tests elsewhere. – Ger Feb 08 '22 at 10:48

0 Answers0