0

I have a class that has multiple methods and I want to store all of the available methods that would be easily accessible in example would be something like this

class Methods:
    def foo(self, a):
        return f'hello {a}' 


    def bar(self, b):
        return f'hello {b}'

    def methods_dict(self, var, **kwargs):
        dic = {
            'me' : self.foo(var),
            'be': self.bar(var)
        }
    return dic

But on runtime my methods_dict() method will execute both of the methods inside of it's dictionary. One one hand I'm planing to store only strings in there and it's really easily accessible, on the other hand i probably would not need to access all of the available methods at once.

Any suggestions ?

I am planning to use those methods as follows

class InheritMethods(Methods):
        def __init__(self, method_name):
            self.method_name = method_name

        def add_to_list(self, input):
            arr = []
            arr.append(self.method_dicts(input)[self.method_name]
            return arr

To clear things up, I am gonna call specific method based on input name, so basically input == method_name
I could do conditional statements like if input == 'foo': do somethings.., but if i end up having a lot of methods, my code is going to be a mess, so i assume(!) that would not be a great idea

nexla
  • 434
  • 7
  • 20

2 Answers2

1

I think you can get what you want with the following. Your exact usecase is still not clear. Please respond if I am heading in the wrong direction.

Using self.__getattribute__() you can get a function by name. Of course you would have to catch exceptions etc.

class Methods:
    def foo(self, a):
        return f'hello {a}' 

    def bar(self, b):
        return f'hello {b}'

class InheritMethods(Methods):
    def __init__(self, method_name):
        self.method_name = method_name

    def add_to_list(self, method_name, input):
        method = getattr(self, method_name)
        result = method(input)
        return [result]

class InheritSingleMethod(Methods):
    def __init__(self, method_name):
        self.add_to_list = self.getattr(self, method_name)

Output

# Any method version
inherit_methods = InheritMethods('a')  # < no use for that argument right?
inherit_methods.add_to_list('foo', 'laurens')
> ['hello laurens']

# Single method version
inherit_single_method = InheritSingleMethod('foo')
inherit_single_method.add_to_list('laurens')
> 'hello laurens'
Laurens Koppenol
  • 2,946
  • 2
  • 20
  • 33
  • oh lord, i was thinking of this solution using getattr(), but that was not the case. That works ! Thank you (: – nexla Aug 14 '19 at 11:50
  • actually, a little improvement to your code, we can pass ```self.method_name``` instead of creating extra parameter in ```add_to_list()``` Since we are instantiating method_name anyways – nexla Aug 14 '19 at 11:53
  • 1
    Unless you refer to Guido van Rossum, the lord is not good at python. He is not too well with snakes in general actually. – Laurens Koppenol Aug 14 '19 at 11:54
  • if you only want to use 1 single function in `add_to_list`, check out `InheritSingleMethod` above! – Laurens Koppenol Aug 14 '19 at 11:56
  • 2
    why are you using `self.__getattribute__(method_name)` instead of just `getattr(self, method_name)`? the latter seems much less magical! – Sam Mason Aug 14 '19 at 12:03
  • @SamMason i was attemtping getattr() but i was getting an error :O – nexla Aug 14 '19 at 12:08
  • @SamMason you are right actually, but it has to be getattr(self, self.method_name) if taking method_name and that's where i got my error – nexla Aug 14 '19 at 12:11
  • cool, didnt know that one worked for classes as well. thanks! – Laurens Koppenol Aug 14 '19 at 12:16
1

If all you want to do is access a method of Methods given the name in a str, use getattr:

name = input()
m = Methods()
getattr(m, name)("bob")
chepner
  • 497,756
  • 71
  • 530
  • 681