You can control how and how many objects are created by providing your class with a method __new__:
class Key(object):
_count = 0
def __new__(cls, s):
if cls._count == 5:
raise TypeError('Too many keys created')
cls._count += 1
return super(Key, cls).__new__(cls, s)
def __init__(self,s):
self.s = s
Key.__new__()Called to create a new instance. here I keep a count of the number created, and if there are too many, an exception is thrown. You can also store the instance pool in a dictionary or control the creation of a new instance in other ways.
, , object.