V
V
Verriant2019-03-24 15:04:10
Python
Verriant, 2019-03-24 15:04:10

How to describe a class to call its methods by specifying their name as a string?

You need to describe the class so that its instance methods are called by passing their name and arguments. Something like this:

MyObject = Test()


a = MyObject('method_1',x,y)# вместо a = MyObject.method_1(x,y)
b = MyObject('method_2',x,y)
c = MyObject('method_3',x,y)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Gornostaev, 2019-03-24
@Verriant

class Test:
    def __call__(self, name, *args, **kwargs):
        method = getattr(self, name)
        return method(*args, **kwargs)

    def method_1(self, x, y)
        return x + y

    ...

PS Follow PEP8, snake case notation is accepted in Python.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question