How to create a limited set of instanceses of a class

madpython madpython at gmail.com
Sat Jul 1 12:28:49 EDT 2006


For the pure theory sake and mind expansion i got a question.
Experimenting with __new__ i found out how to create a singleton.
class SingleStr(object):
    def __new__(cls,*args,**kwargs):
        instance=cls.__dict__.get('instance')
        if instance:
            return instance
        cls.instance=object.__new__(cls,*args,**kwargs)
        return cls.instance

What if i need to create no more than 5 (for example) instances of a
class. I guess that would be not much of a problema but there is a
complication. If one of the instances is garbagecollected I want to be
able to spawn another instance. Maybe it's difficult to perceive what i
said so think of a limited number of sockets. Wherenever one is freed
it can be captured again.
I believe that this type of the design pattern was described in
"Thinking in Java" but there was a special method finalize()
utilized, that is called every time when gc() is about to clean up an
unreferenced object. By using this method a counter of active instances
could be easily implemented. What is the pythonic approach to this
problema?




More information about the Python-list mailing list