Call method from string

前端 未结 4 1146
不思量自难忘°
不思量自难忘° 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:22

    Your class has been declared as an "old-style class". I recommend you make all your classes be "new-style classes".

    The difference between the old and the new is that new-style classes can use inheritance, which you might not need right away. But it's a good habit to get into.

    Here is all you have to do to make a new-style class: you use the Python syntax to say that it inherits from "object". You do that by putting parentheses after the class name and putting the name object inside the parentheses. Like so:

    class CallMe(object): # Class
    
       def App(): # Method one
    
          ...
    
       def Foo(): # Method two
    
          ...
    

    As I said, you might not need to use inheritance right away, but this is a good habit to get into. There are several questions here on StackOverflow to the effect of "I'm trying to do X and it doesn't work" and it turns out the person had coded an old-style class.

提交回复
热议问题