问题描述
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 个,它应该引发异常.
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.
正如我们在 Python 中所知,__new__
是在需要创建实例时调用的方法.我试图写一些代码,但没有奏效.
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.
当我运行这段代码时,它总共运行了 6 次.请问有人可以在这里指导我吗?我也试过在谷歌上检查,但没有得到任何正确的代码.
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.
推荐答案
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()
这篇关于在 Python 中限制对象创建的程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!