Program To Restrict Object Creation In Python
class object_restrict(object): _count = 0 def __new__(cls): if cls._count > 5: raise TypeError('Too many keys created') cls._count += 1
Solution 1:
as pointed out by Wilfred there's a problem with the _count
check or variable initialization. but i would like to point out another problem which is that you are not returning the instance of the object. if you have this:
classA(object):
_count = 0def__new__(cls):
if cls._count > 5:
raise Exception('Too many instances were created')
cls._count += 1def__init__(self):
pass
asd = A()
print asd
will output:
$ None
you should return the instance of the object, which is actually __new__
responsibility:
classA(object):
_count = 0def__new__(cls):
if cls._count >= 5: # @Wilfred fixraise Exception('Too many instances were created')
cls._count += 1returnsuper(A, cls).__new__(cls) # returning the instancedef__init__(self):
pass
asd = A()
print asd
output:
$ <__main__.A object at 0x7f5ddad7db10>
Solution 2:
class object_restrict(object):
_count = 0
def __new__(cls):
cls._count += 1
if cls._count > 5:
raise TypeError("Too many keys created")
print cls._count, "object created"
def __init__(self):
pass
k = object_restrict()
k1 = object_restrict()
k2 = object_restrict()
k3 = object_restrict()
k4 = object_restrict()
k5 = object_restrict()
Solution 3:
You init your _count variable to 0.
First call : _count = 0
Sixth call : _count = 5
, So he can create your object.
Init _count = 1
or update your if condition to cls._count >= 5:
Solution 4:
A class that allows maximum 5 objects to be instantiated (Python 3):
class RestrictClass(object):
__count = 0
def __new__(cls):
if cls.__count>=5:
raise TypeError("Already instantiated")
cls.__count+=1
return super(RestrictClass,cls).__new__(cls)
def __init__(self):
pass
def showNumberOfObjects(self):
print("Number of objects are now: "+str(self.__count))
k1 = RestrictClass()
k1.showNumberOfObjects()
k2 = RestrictClass()
k2.showNumberOfObjects()
k3 = RestrictClass()
k3.showNumberOfObjects()
k4 = RestrictClass()
k4.showNumberOfObjects()
k5 = RestrictClass()
k5.showNumberOfObjects()
k6 = RestrictClass()
k6.showNumberOfObjects()
Output:
Numberof objects are now: 1Numberof objects are now: 2Numberof objects are now: 3Numberof objects are now: 4Numberof objects are now: 5Traceback (most recent call last):
File"/media/arsho/Documents/pyPrac/object.py", line 27, in <module>
k6 = RestrictClass()
File"/media/arsho/Documents/pyPrac/object.py", line 5, in __new__
raise TypeError("Already instantiated")
TypeError: Already instantiated
Post a Comment for "Program To Restrict Object Creation In Python"