late bindings ???

Cousin Stanley CousinStanley at HotMail.com
Mon Dec 2 11:59:41 EST 2002


|| ...
|| If method names would, you can use  getattr.
|| getattr(obj, 'xxx') is equivalent to obj.xxx
|| ...

Thanks to Peter Hansen, I've found that using the getattr method
seems to work well for using a list of defined method names
in a list as a simple way to combine those methods into different programs ...

Python code and a few short .WAV  files that it plays ...
http://fastq.com/~sckitching/Python/xMethods.zip
[ 295 KB ]

Cousin Stanley

---------------------------------------------------------------------

"""
     xMethods.py

       Invokes methods of aClass  on anObject of aClass
       where   the methods are referenced thru a String variable,
       actually in this demo program, a list of strings ...

       The method reference  mRef  is obtained
       thru the  getattr()  method

     NewsGroup Reference
       Peter Hansen
       comp.lang.python
       2002-06-06

     Modified
       Stanley C. Kitching
         2002-06-08
           Added applyMethods
           Added xProgram Lists
           Added Sounds
"""

import sys
import winsound

class aClass :

  def Method_0( self ) :
      print '\n\t ...    Greetings     ... '
      print   '\t ...      huMon       ... '

  def Method_1( self ) :
      print '\n\t ...  eenGa baZeenGa  ... '
      print   '\t ...  rinGa da dinGa  ... '

      xSound( 'Ding.wav' )

  def Method_2( self ) :
      print '\n\t ...    imA baZimeA   ... '
      print   '\t ...  rinGa yo chimeA ... '

      xSound( 'WindChime.wav' )

  def Method_3( self ) :
      print '\n\t ...   onGo baZonGO   ... '
      print   '\t ...  bonGo da gonGo  ... '

      xSound( 'Gong.wav' )

  def Method_4( self ) :
      print '\n\t ...      Adios       ... '
      print   '\t ...      huMon       ... '

      nSnorts = 3

      for i in range( 1 , nSnorts ) :

          xSound( 'Snort.wav' )

      xSound( 'Meep_Meep.wav' )

def xSound( xFile ) :

    sFolder = 'Sounds/'

    sFile   = sFolder + xFile

    winsound.PlaySound( sFile , winsound.SND_FILENAME )


# -------------------------------------------------------

def applyMethods( xObject , methodList ) :

    for xMethod in methodList :

        mRef = getattr( xObject , xMethod )

        mRef()

anObject = aClass()

aProgram = [ 'Method_0' , 'Method_1' , 'Method_2' , 'Method_3' ]
bProgram = [ 'Method_3' , 'Method_3' ]
cProgram = [ 'Method_2' , 'Method_1' , 'Method_4' ]

applyMethods( anObject , aProgram )
applyMethods( anObject , bProgram )
applyMethods( anObject , cProgram )






More information about the Python-list mailing list