Julius B. Lucks/Projects/Python Articles/Design Patterns In Scientific Programming

From OpenWetWare
Jump to navigationJump to search

This is not an article, but a scratch pad that will eventually be massaged into an article.

Patterns in Python

Singleton

See Jeff Pitman's solution in the comment section in the Python Cookbook. Test code looks like

<syntax type="python">

class Singleton(object):

   """The Singleton Class Definition"
   def __new__(cls,*p,**k):
       if not '_the_instance' in cls.__dict__:
           cls._the_instance = object.__new__(cls)
       return cls._the_instance
  1. Create 3 instances of Singleton

s = Singleton() t = Singleton() q = Singleton()

  1. Note that you can see that they are the same
  2. object by the hex id of the objects

print s print t print q

  1. You can also see that since they have the
  2. same id's

id(s) == id(t) == id(q)

  1. Now try an inheritance example

class SingletonChild(Singleton):

   """Inherited from the Singleton class."""
   pass

w = SingletonChild() m = SingletonChild()

  1. Note w and m are the same

id(w) == id(m)

  1. But w and s are different

id(w) == id(s)

</syntax>


Chain of Responsibility


<syntax type="python"> class Event:

   def __init__( self, name ):
       self.name = name

class Widget:

   def __init__( self, parent = None ):
       self.__parent = parent
   def Handle( self, event ):
       handler = 'Handle_' + event.name
       if hasattr( self, handler ):
           method = getattr( self, handler )
           method( event )
       elif self.__parent:
           self.__parent.Handle( event )
       elif hasattr( self, 'HandleDefault' ):
           self.HandleDefault( event )  

</syntax>