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

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

    Here's a quick and dirty example of how a class could fire different versions of a save method depending on which operating system it's being executed on using getattr().

    import os
    
    class Log(object):
        def __init__(self):
            self.os = os.name
        def __getattr__(self, name):
            """ look for a 'save' attribute, or just 
              return whatever attribute was specified """
            if name == 'save':
                try:
                    # try to dynamically return a save 
                    # method appropriate for the user's system
                    return getattr(self, self.os)
                except:
                    # bail and try to return 
                    # a default save method
                    return getattr(self, '_save')
            else:
                return getattr(self, name)
    
        # each of these methods could have save logic specific to 
        # the system on which the script is executed
        def posix(self): print 'saving on a posix machine'
        def nt(self): print 'saving on an nt machine'
        def os2(self): print 'saving on an os2 machine'
        def ce(self): print 'saving on a ce machine'
        def java(self): print 'saving on a java machine'
        def riscos(self): print 'saving on a riscos machine'
        def _save(self): print 'saving on an unknown operating system'
    
        def which_os(self): print os.name
    

    Now let's use this class in an example:

    logger = Log()
    
    # Now you can do one of two things:
    save_func = logger.save
    # and execute it, or pass it along 
    # somewhere else as 1st class:
    save_func()
    
    # or you can just call it directly:
    logger.save()
    
    # other attributes will hit the else 
    # statement and still work as expected
    logger.which_os()
    

提交回复
热议问题