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

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

    Another use of getattr() in implementing a switch statement in Python. It uses both reflection to get the case type.

    import sys
    
    class SwitchStatement(object):
        """ a class to implement switch statement and a way to show how to use gettattr in Pythion"""
    
        def case_1(self):
            return "value for case_1"
    
        def case_2(self):
            return "value for case_2"
    
        def case_3(self):
            return "value for case_3"
    
        def case_4(self):
            return "value for case_4"
    
        def case_value(self, case_type=1):
            """This is the main dispatchmethod, that uses gettattr"""
            case_method = 'case_' + str(case_type)
            # fetch the relevant method name
            # Get the method from 'self'. Default to a lambda.
            method = getattr(self, case_method, lambda: "Invalid case type")
            # Call the method as we return it
            return method()
    
    def main(_):
        switch = SwitchStatement()
        print swtich.case_value(_)
    
    if __name__ == '__main__':
        main(int(sys.argv[1]))
    
    0 讨论(0)
  • 2020-11-22 09:48

    For me, getattr is easiest to explain this way:

    It allows you to call methods based on the contents of a string instead of typing the method name.

    For example, you cannot do this:

    obj = MyObject()
    for x in ['foo', 'bar']:
        obj.x()
    

    because x is not of the type builtin, but str. However, you CAN do this:

    obj = MyObject()
    for x in ['foo', 'bar']:
        getattr(obj, x)()
    

    It allows you to dynamically connect with objects based on your input. I've found it useful when dealing with custom objects and modules.

    0 讨论(0)
提交回复
热议问题