Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>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 <code>getattr()</code>.</p> <pre><code>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 </code></pre> <p>Now let's use this class in an example:</p> <pre><code>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() </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload