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

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

    # getattr
    
    class hithere():
    
        def french(self):
            print 'bonjour'
    
        def english(self):
            print 'hello'
    
        def german(self):
            print 'hallo'
    
        def czech(self):
            print 'ahoj'
    
        def noidea(self):
            print 'unknown language'
    
    
    def dispatch(language):
        try:
            getattr(hithere(),language)()
        except:
            getattr(hithere(),'noidea')()
            # note, do better error handling than this
    
    dispatch('french')
    dispatch('english')
    dispatch('german')
    dispatch('czech')
    dispatch('spanish')
    

提交回复
热议问题