Python variable method name

How can you execute a method by specifying its name from another method that is in the same class with the called method? Like this:

class Class1: def __init__(self): pass def func1(self, arg1): # some code def func2(self): function = getattr(sys.modules[__name__], "func1") # apparently this does not work 

Any suggestion?

+8
function variables python methods
source share
2 answers

how about getattr(self, "func1") ? Also, do not use the name function

For example:

 >>> class C: ... def f1(self, arg1): print arg1 ... def f2(self): return getattr(self, "f1") ... >>> x=C() >>> x.f2()(1) 1 
+9
source share

You should get the attribute from the class, not from the module.

 def func2(self): method = getattr(self, "func1") method("arg") 

But you should also check that it is callable.

 if callable(method): method("arg") 

This will avoid calling what you did not expect to receive. You may want to create your own exception here if it cannot be raised.

+5
source share

All Articles