Julius B. Lucks/Projects/Python Articles/Design Patterns In Scientific Programming
From OpenWetWare
(Redirected from Lucks/Design Patterns with Science)
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
- Create 3 instances of Singleton
s = Singleton() t = Singleton() q = Singleton()
- Note that you can see that they are the same
- object by the hex id of the objects
print s print t print q
- You can also see that since they have the
- same id's
id(s) == id(t) == id(q)
- Now try an inheritance example
class SingletonChild(Singleton):
"""Inherited from the Singleton class.""" pass
w = SingletonChild() m = SingletonChild()
- Note w and m are the same
id(w) == id(m)
- But w and s are different
id(w) == id(s)
</syntax>
Chain of Responsibility
- Very useful for handling dependincies in inputs for pipeline code
- See Design Patterns in Python
<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>