Call method from string

前端 未结 4 1228
不思量自难忘°
不思量自难忘° 2020-12-28 12:27

If I have a Python class, and would like to call a function from it depending on a variable, how would I do so? I imagined following could do it:

class CallM         


        
4条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-28 13:24

    You can do this:

    getattr(CallMe, variable)()
    

    getattr is a builtin method, it returns the value of the named attributed of object. The value in this case is a method object that you can call with ()

提交回复
热议问题