Here are some Python design patterns. For memory, a design pattern is a template for how to solve a problem that can be used in many different situations.


A singleton is a class that can be instantiated only one time:

class C:
    __single = None
        if C.__single:
            raise C.__single
        __single = self        

Chain of responsibility

Often used in GUI event handling, the idea is to buil a chain of object that, given an event, can handle it of transmit it to the parent.

class Event:
    def __init(self, name)__: = name

class Widget:
    def __init(self, parent = None)__:
        __self.parent = parent
    def Handle(self, event):
        handler = 'Handle_' +
        if hasattr(self, handler):
            method = getattr(self, handler)
        elif self.__parent:

It is used as follows:

class MainWindow(Widget):
    def Handle_close():
    def HandleDefault():
class Dialog(Widget):
    def Handle_ok():
mw = MainWindow()
d = Dialog(mw)
e = Event('close')


In C++ in would be implemented by two classes sharing the same parent class. In Python:

class Proxy:
    def __init(self, subject)__:
        self.__subject = subject
    def __getattr(self, name)__:
        return self.__getattr(self.__subject, name)__

It is used as follows:

class RGB:
    def __init__( self, red, green, blue ):
        self.__red = red
        self.__green = green
        self.__blue = blue
    def Red( self ):
        return self.__red
    def Green( self ):
        return self.__green
    def Blue( self ):
        return self.__blue
class NoBlueProxy(Proxy):
    def Blue( self ):
        return 0
c = RGB(100, 100, 100)
b = Proxy(c)
nb = NoBlueProxy(c)