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()
我似乎对如何在Python中限制类的对象数量有一些疑问。我被要求编写一个程序,我应该把条件放在我们只能创建一个类的5个实例的情况下,如果我们尝试创建超过5个,它应该引发异常。
正如我们在Python中所知,__new__
是在需要创建实例时调用的方法。我试着写一些代码,但它没有用。
当我运行此代码时,它运行了6次。请有人在这指导我吗?我也试过检查谷歌,但没有得到任何正确的代码。
答案 0 :(得分:1)
正如Wilfred指出的那样_count
检查或变量初始化存在问题。但我想指出另一个问题,即你没有返回对象的实例。如果你有这个:
class A(object):
_count = 0
def __new__(cls):
if cls._count > 5:
raise Exception('Too many instances were created')
cls._count += 1
def __init__(self):
pass
asd = A()
print asd
将输出:
$ None
你应该返回对象的实例,实际上是__new__
责任:
class A(object):
_count = 0
def __new__(cls):
if cls._count >= 5: # @Wilfred fix
raise Exception('Too many instances were created')
cls._count += 1
return super(A, cls).__new__(cls) # returning the instance
def __init__(self):
pass
asd = A()
print asd
输出:
$ <__main__.A object at 0x7f5ddad7db10>
答案 1 :(得分:1)
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()
答案 2 :(得分:0)
您将_count变量初始化为0。
首先致电:_count = 0
第六个电话:_count = 5
,所以他可以创建你的对象。
初始化_count = 1
或将您的if条件更新为cls._count >= 5:
答案 3 :(得分:0)
允许实例化最多5个对象的类(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()
输出:
Number of objects are now: 1
Number of objects are now: 2
Number of objects are now: 3
Number of objects are now: 4
Number of objects are now: 5
Traceback (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