class object_restrict(object):
_count = 0
def __new__(cls):
if cls._count > 5:
raise TypeError("Too many keys created")
cls._count += 1
print "object created"
def __init__(self):
pass
k = object_restrict()
k1 = object_restrict()
k2 = object_restrict()
k3 = object_restrict()
k4 = object_restrict()
k5 = object_restrict()
It seems I have some questions regarding how can we restrict the number of objects for a class in Python. I have been asked to write a program where I should put the condition where we can create only 5 instances of a class, and if we try to create more than 5, it should raise an exception.
As we know in Python, __new__ is the method which is get called whenever an instance needs to be created. I tried to write some code, but it didn't work.
When I ran this code, it ran for all 6 times. Please can somebody guide me here? I also tried checking on Google but didn't get any proper code.