Design Pattern and Python: Any book recommendation? Your view?
Roy Smith
roy at panix.com
Thu Nov 3 21:46:53 EDT 2011
In article
<6097694.446.1320366784098.JavaMail.geo-discussion-forums at prap37>,
Anthony Kong <anthony.hw.kong at gmail.com> wrote:
> Sorry to resurrect this topic. By google search the last discussion was in
> 2003.
What? We're bring it up again, SO SOON!?
> I would like to find out what is the current prevailing view or consensus (if
> any) on the use of Design Pattern in python?
> [...]
> I myself pretty much subscribe to the view that the nature of python language
> actually do away much of the need of the use of DP
To a certain extent, I agree. I don't have a huge amount of experience
in Design Patterns, but have read (years ago) the obligatory Gang Of
Four book. My impression was that much of that book was about how to
build sane data structures to do useful things given the uber-bondage
constraints of the C++ and Java typing systems.
For example, let's look at Singleton. It's a useful pattern. Here's
how I would implement Singleton in Python (hand-waving a bit about the
syntax details):
class Printer:
thePrinter = None
@staticmethod
def get():
if Printer.thePrinter is None:
Printer.thePrinter = Printer()
return thePrinter
def print(self):
"print some stuff"
whatever
That seems to cover everything Singleton needs to do. In your
application code, you do:
myPrinter = Printer.get()
myPrinter.print(....)
and you can sleep easy knowing you've got the same Printer instance
every time. The GoF version for C++ is filled with minutia about
private constructors and assignment operators. All that stuff is
important to get right in C++, but it has nothing to do with Singleton,
per se. It's just all the gunk you have to worry about to correctly
implement Singleton in C++.
More information about the Python-list
mailing list