How to limit object creation

Consider the 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 10,000 keys. Is it possible to control the creation of an object by a class key, for example, we cannot create more than 5 objects of a key class. The loop should not be changed in any way.

+4
source share
2 answers

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.

+7

import weakref
import random

class FiveElementType(type):
    def __init__(self, name, bases, d):
        super(FiveElementType, self).__init__(name, bases, d)
        self.__cache = weakref.WeakValueDictionary()

    def __call__(self, *args):
       if len(self.__cache) == 5:
           return random.choice(self.__cache.values())
       else:
           obj = super(FiveElementType, self).__call__(*args)
           self.__cache[len(self.__cache)] = obj
           return obj

class Key(object):
    __metaclass__ = FiveElementType
    def __init__(self, s):
       self.s = s

. , , .

0

All Articles