1

I know the simplified example below is embarrassingly ugly ... hence why I have come to SO to share it with the world.

I would like to be able to call a class method from cls, specifying the particular method within callmethod.

class cls(object):
    def __init__(self, var1):
        self.var1 = var1
    def method1(self):
        return self.var1 ** 2
    def method2(self):
        return self.var1 ** 3

def callmethod(method, var1):
    methods = {'method1' : cls(var1).method1(),
               'method2' : cls(var1).method2()
              }
    return methods[method]

callmethod('method1', 2)
Out[56]: 4

Is there a way to go about this without creating a (possibly large and cumbersome) dict that links a string form of each method to the actual thing?

2
  • I mean just using getattr would negate the need for that dictionary, but I don't see how your real example and abstract example are connected at all. Commented Jun 9, 2017 at 3:27
  • 2
    operator.methodcaller Commented Jun 9, 2017 at 3:31

1 Answer 1

2

What you're looking for is likely just:

def callmethod(method, arg)
    inst = cls(arg)
    return getattr(inst, method)()

You can think of a.b as a syntax sugar for getattr(a, "b")

Sign up to request clarification or add additional context in comments.

1 Comment

or think of getattr(a, "b") as a function / dynamic way of doing a.b :P

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.