Consider following example
class Key:
    def __init__(self, s):
        self.s = s
d = {}
for x in range(1, 10000):
    t = Key(x)
    d[t] = x
This will create 10000 keys. Is it possible to control the object creation of class key, for example we cannot create more than 5 objects of key class. The loop should not be changed in any ways.
You can control how, or how many objects are created by giving your class a __new__ method:
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__() is called to create a new instance; here I keep a count of how many are created, and if there are too many, an exception is raised. You could also keep a pool of instances in a dictionary, or control creating of new instance in other ways.
Note that this only works for new-style classes, inheriting from object.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With