开发者

python variable method name

开发者 https://www.devze.com 2023-03-29 16:42 出处:网络
How can you execute a method by giving its name, from another method that is in the sa开发者_Go百科me class with the called method? Like this:

How can you execute a method by giving its name, from another method that is in the sa开发者_Go百科me 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?


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消