How can you execute a method by giving 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?
Method name in PythonUse only lowercase in method names. An underscore should separate words in a method name. Non-public method name should begin with a single underscore. Use two consecutive underscores at the beginning of a method name, if it needs to be mangled.
One more thing that can be called function name (though it hardly is) is the name of a variable or an attribute where reference to that function is stored.
The __name__ variable (two underscores before and after) is a special Python variable. It gets its value depending on how we execute the containing script. Sometimes you write a script with functions that might be useful in other scripts as well. In Python, you can import that script as a module in another script.
how about getattr(self, "func1")
? Also, avoid using 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
You should get the attribute from the class, not the module.
def func2(self):
method = getattr(self, "func1")
method("arg")
But you should also check that it's callable.
if callable(method):
method("arg")
This will avoid calling something that you didn't expect to get. You may want to raise your own exception here if it is not callable.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With