应该使用哪些内置的Python异常来表示已经创建了类的实例(例如MCWindow
)?接下来是这样的:
window = MCWindow()
try:
aWindow = MCWindow()
except DontMakeAnotherOneOfTheseInstancesException:
print("Whoops") # Always the best way to handle exceptions :)
在这里,单例模式可能更合适,但我仍然想知道对于这种情况是否存在内置的异常。你知道吗
Tags:
事实上,只要稍加调整,你就能做到
observer类是存储状态的地方,singleton类是请求中的类,您只想将其限制为一个实例,您可以创建许多类,如
singleton
,但只有一个Observer
来保持所有类的状态。你知道吗试试上面的代码,玩得开心。。它对我有用:))
更新创建singleton而不引发异常
这是要实例化为singleton的类
用法
我不这么认为。 您可能可以使用RuntimeError或您自己继承的异常。 Here您可以找到所有内置异常及其描述的列表。你知道吗
不过,正如您所说,google搜索“python singleton”会给您提供许多更好的解决方案。你知道吗
单例模式在
python
中并不常见。通常,使用模块代替对象实例。你知道吗换句话说,没有准确的内在例外。创建自己的,或切换到模块。你知道吗
注意:可以使用一点元编程来创建一个类,该类在实例化时总是返回相同的对象,不涉及异常。
相关问题 更多 >
编程相关推荐