将类限制为最多一个实例时要抛出哪个Python异常?
哪些内置Python异常应该用来表示我的类的实例(例如,将类限制为最多一个实例时要抛出哪个Python异常?,python,exception,singleton,Python,Exception,Singleton,哪些内置Python异常应该用来表示我的类的实例(例如,MCWindow)已经创建?它将如下所示: window = MCWindow() try: aWindow = MCWindow() except DontMakeAnotherOneOfTheseInstancesException: print("Whoops") # Always the best way to handle exceptions :) 单例模式在这里可能更合适,但我仍然想知道这种情况是否存在内置异
MCWindow
)已经创建?它将如下所示:
window = MCWindow()
try:
aWindow = MCWindow()
except DontMakeAnotherOneOfTheseInstancesException:
print("Whoops") # Always the best way to handle exceptions :)
单例模式在这里可能更合适,但我仍然想知道这种情况是否存在内置异常。我不这么认为。
您可能会使用RuntimeError或您自己继承的异常。
您可以找到所有内置异常及其描述的列表
虽然,正如您所说,通过谷歌搜索“python singleton”可以为您提供许多更好的解决方案。在
python
中,singleton模式并不常见。通常,使用模块代替对象实例
换句话说,没有准确的内置例外。创建自己的,或切换到模块
注意:可以使用一些元编程来创建一个类,该类在实例化时总是返回相同的对象,不涉及任何异常。实际上,只要稍加调整,您就可以做到这一点
# python object singleton
class Observer():
pass
observe = Observer()
class singleton():
def __init__(self,):
if observe.__dict__.has_key(self.__class__.__name__):
raise Exception, 'Only one instance of the same "%s" class is allowed' % self.__class__.__name__
observe.__dict__[self.__class__.__name__]=True
def some_method(self,):
# roll your own code
pass
one = singleton()
two = singleton() # will raise an error
observer类是存储状态的地方,singleton类是请求中的类,您希望将其限制为仅一个实例,您可以创建许多类,如singleton
,但只有一个observer
来保持所有类的状态
试试上面的代码,玩得开心。。它对我有用:))
更新--创建单例而不引发异常
class Observer():
def __init__(self,):
self.error = None
def __setattr__(self,class_name,instance):
if not self.__dict__.has_key(instance.__class__.__name__):
self.__dict__[class_name]=instance
else:
self.error = 'You are only allowed to creat intance once'
def __getattr__(self,class_name):
if self.__dict__.has_key(class_name):
return self.__dict__[class_name]
else:
return None
这是要实例化为singleton的类
class test():
pass
用法
对此没有内置的例外,因为这不是一个有用或有意义的操作/信号,因为这样的限制通常是毫无意义的,当没有限制时,有更好的方法来实施它。为什么必须强制只创建一个实例?RuntimeError用于“当检测到不属于任何其他类别的错误时”,这是最适合的内置异常。但是使用自定义异常可能更好,或者完全不使用前面提到的单例。@SimonT,请检查下面的答案。我不确定为我的
MCWindow
使用模块是否适合我的情况,但这对未来的项目是一个很好的建议。使用Python进行元编程目前有点超出我的范围,但谢谢。@uʍopǝpısdn,我已经做了一些调整,不需要元编程,请查看我在本页中的答案。感谢您在这里为帮助实现单例模式所做的努力。但是,我不认为引发一个异常
是最好的选择,因为这会使处理异常变得更加困难,因为编码人员必须捕获所有异常
s,然后找出问题所在。@SimonT,检查我上次的更新以创建一个不引发异常的单例。。让我知道它是否有帮助我相信你给出的代码值得称赞。然而,由于我的问题是关于内置Python异常的,而不是关于单例模式的,所以我不能给出太多其他的评价。不过,我会充分利用你的解决方案。
observe = Observer()
observe.test = test() # This will be created and bound to the variable
observe.test = test() # This will not be created nor bound, but will generate an error msg in observe.error
if not observe.error:
print 'created successfully'
else:
print 'Encountered a problem: %s, only this instance has been created: %s' % (observe.error,observe.test)