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

前端 未结 14 1622
孤独总比滥情好
孤独总比滥情好 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:35

    I have tried in Python2.7.17

    Some of the fellow folks already answered. However I have tried to call getattr(obj, 'set_value') and this didn't execute the set_value method, So i changed to getattr(obj, 'set_value')() --> This helps to invoke the same.

    Example Code:

    Example 1:

        class GETATT_VERIFY():
           name = "siva"
           def __init__(self):
               print "Ok"
           def set_value(self):
               self.value = "myself"
               print "oooh"
        obj = GETATT_VERIFY()
        print getattr(GETATT_VERIFY, 'name')
        getattr(obj, 'set_value')()
        print obj.value
    

提交回复
热议问题