0

Let's say you have this:

class Functions():
    def __init__(self):
        pass;

    def sum(self, x, y):
        return x + y;

f = Functions();
print(f[0](1,2));

no, that's not how my code works but it's a example

Basically, I need a way for the last line to print 3, kind of like a way to index Class functions from number. (I would like a Pythonic solution to this if possible)

I've thought of manually setting the "wiring" to do this, but it would be very annoying, as I will be constantly adding new functions.

Is there any magic method for this? I'm pretty sure that __getitem__ is a good resource for this, but I have found myself uncapable of wrapping it's usage around this issue.

Thanks in advance, any help is valuable.

1 Answers1

0

Building off of one of the answers to this question, you can do this:

f = Functions()
funcs = [func for func in dir(Functions) if callable(getattr(Functions, func)) and func.find('__') == -1]
print(getattr(Functions, funcs[0])(f, 1, 2))

Or you could wrap it in your class like this, using __getitem__ as you mentioned:

class Functions():
    def __init__(self):
        pass;

    def __getitem__(self, i):
        funcs = [func for func in dir(Functions) if callable(getattr(Functions, func)) and func.find('__') == -1]
        return getattr(self, funcs[i])

    def sum(self, x, y):
        return x + y;

The only issue with these approaches is that it won't preserve the original ordering of the function definitions, instead it will be in alphabetical order

awarrier99
  • 3,628
  • 1
  • 12
  • 19