Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python variable method name

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?

like image 973
Shaokan Avatar asked Aug 20 '11 04:08

Shaokan


People also ask

How do you name a method in Python?

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.

Is function name a variable Python?

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.

What is the __ name __ variable in Python?

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.


2 Answers

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
like image 65
Foo Bah Avatar answered Oct 13 '22 10:10

Foo Bah


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.

like image 41
Keith Avatar answered Oct 13 '22 09:10

Keith