What is getattr() exactly and how do I use it?

前端 未结 14 1652
孤独总比滥情好
孤独总比滥情好 2020-11-22 09:04

I\'ve recently read about the getattr() function. The problem is that I still can\'t grasp the idea of its usage. The only thing I understand about getattr() is

14条回答
  •  一生所求
    2020-11-22 09:45

    I think this example is self explanatory. It runs the method of first parameter, whose name is given in the second parameter.

    class MyClass:
       def __init__(self):
          pass
       def MyMethod(self):
          print("Method ran")
    
    # Create an object
    object = MyClass()
    # Get all the methods of a class
    method_list = [func for func in dir(MyClass) if callable(getattr(MyClass, func))]
    # You can use any of the methods in method_list
    # "MyMethod" is the one we want to use right now
    
    # This is the same as running "object.MyMethod()"
    getattr(object,'MyMethod')()
    

提交回复
热议问题