[Tutor] Borg di borg di borg (or: Swedish chef)
Albert-Jan Roskam
fomcl at yahoo.com
Mon Sep 24 12:02:55 CEST 2012
Hi Pythonistas,
I have three classes, Generic, Test and Test2. Generic contains a load method that loads a file. This may only be done once, as a file_read_open error is returned if the file is open already and an attempt is made to re-open it. The file may be opened from Test or Test2. After a lot of playing with a "counter" class variable, I realized this may be a legitimate use case for the Borg pattern (http://code.activestate.com/recipes/66531). Is the code below the right way to apply the Borg pattern?
somefile = "/home/albertjan/Desktop/somefile.txt"
class Borg(object):
counter = 0
_state = {}
def __init__(self):
self.__dict__ = self._state
class Generic(Borg):
def __init__(self):
super(Generic, self).__init__()
self.loaded = self.load()
print "@state", Borg._state
print self.loaded
def load(self):
""" Only one file at a time may be opened, or else
there will be an open-read error"""
Borg.counter += 1
return open(somefile)
class Test(Generic):
def __init__(self):
if Borg.counter == 0:
self.theFile = Generic().load()
self.theFile = Borg._state["loaded"]
print self.theFile
class Test2(Generic):
def __init__(self):
if Borg.counter == 0:
self.theFile = Generic().load()
self.theFile = Borg._state["loaded"]
print "---", self.theFile
print Borg.counter
b2 = Test2()
b1 = Test()
Thank you in advance!
Regards,
Albert-Jan
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
All right, but apart from the sanitation, the medicine, education, wine, public order, irrigation, roads, a
fresh water system, and public health, what have the Romans ever done for us?
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
More information about the Tutor
mailing list