首页 Python python – 如何动态调用类中的方法使用方法名分配给变量

python – 如何动态调用类中的方法使用方法名分配给变量

这个问题在这里已经有一个答案: Calling a function of a module from a string with the function’s name in Python10个 class MyClass: def __init__(self, i

这个问题在这里已经有一个答案:>
Calling a function of a module from a string with the function’s name in Python10个

class MyClass:

    def __init__(self,i):
          self.i = i

    def get(self):
          func_name = 'function' + self.i
          self.func_name() # <-- this does NOT work.

    def function1(self):
          //do something

    def function2(self):
          //do something

我得到的错误:
TypeError:’str’对象不可调用

有人可以帮助这个.我已经尝试了很多排列和组合,但没有用! (注:’self.func_name’也不行)

解决方法

def get(self):
      def func_not_found(): # just in case we dont have the function
         print "No Function "+self.i+" Found!"
      func_name = 'function' + self.i
      func = getattr(self,func_name,func_not_found) 
      func() # <-- this should work!

本文来自网络,不代表青岛站长网立场。转载请注明出处: https://www.0532zz.com/html/kaifa/python/20210111/15168.html
上一篇
下一篇

作者: dawei

【声明】:青岛站长网内容转载自互联网,其相关言论仅代表作者个人观点绝非权威,不代表本站立场。如您发现内容存在版权问题,请提交相关链接至邮箱:bqsm@foxmail.com,我们将及时予以处理。

为您推荐

返回顶部