I've been working with the Borg design pattern from here:
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66531

and I'm having problems subclassing it.

I'm a newbie, so I've probably missed something obvious.

I want two Borg-like classes where all instances share state within each
class, but not between them. This is what I tried:

py> class Borg:
py>     _shared_state = {}
py>     def __init__(self):
py>         self.__dict__ = self._shared_state
py> 
py> class Duck(Borg):
py>     def __init__(self):
py>         Borg.__init__(self)
py>         self.covering = "feathers" # all ducks are feathered
py>
py> class Rabbit(Borg):
py>     def __init__(self):
py>         Borg.__init__(self)
py>         self.covering = "fur" # all rabbits are furry
py>
py> bugs = Bunny(); daffy = Duck()
py> daffy.covering
'feathers'
py> bugs.covering
'feathers'

Not what I wanted or expected. What I wanted was for the subclasses Rabbit
and Duck to each inherit Borg-like behaviour, but not to share state with
any other Borgs. In other words, all Ducks share state, and all Rabbits
share state, but Ducks and Rabbits do not share state with each other.

I now see why Ducks and Rabbits are sharing state: they both share the
same __dict__ as all Borg instances. But I don't see how to get the
behaviour I want. (Except by cutting and pasting the Borg code into each
one.) Can anyone help?

Thanks,



Steven.






-- 
http://mail.python.org/mailman/listinfo/python-list

Reply via email to