Sunday, April 6, 2008

Singletons in Python

Talk about confusion. I was thinking 12 ways to do it that I've seen. Probably more that that!

Here's a post that's pretty fresh that seems to be the direction to take.

Here's a first stab at it that works!!! It's a simplified version of what was in that post.

It's pretty messy. I'm guessing at what the author is getting at though. His code only needs to be implemented in the root class?

WaterBlock_singleton = None

class WaterBlock(Block):
class __metaclass__(type):
def __call__(cls, *args, **kwargs):
return cls.__new__(cls, *args, **kwargs)
def __new__(cls, *args, **kargs):
global WaterBlock_singleton
if not WaterBlock_singleton:
obj = object.__new__(cls)
WaterBlock_singleton = obj
obj.__init__(*args, **kargs)
return WaterBlock_singleton
def __init__(self):
super(WaterBlock, self).__init__() = BlockVu(self, 'Water Block.png')

No comments: