Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to restrict object creation

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.

like image 952
asb Avatar asked Mar 18 '23 13:03

asb


1 Answers

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.

like image 64
Martijn Pieters Avatar answered Mar 28 '23 17:03

Martijn Pieters