__init__
在python中引发异常可以吗?我有这段代码:
class VersionManager(object):
def __init__(self, path):
self._path = path
if not os.path.exists(path): os.mkdir(path)
myfunction(path)
第二行可能会导致异常。在这种情况下,该对象将无法正确初始化。有没有更好的方法来处理其中的代码__init__
可能引发异常的情况?
编辑添加os.mkdir
检查以查看目录是否存在后,向函数添加了调用
在中引发异常是完全可以的__init__
。然后,您可以使用包裹对象的初始化/创建调用try/except
并对异常做出反应。
一个潜在的奇怪结果__del__
是无论如何都会运行:
class Demo(object):
def __init__(self, value):
self.value=value
if value==2:
raise ValueError
def __del__(self):
print '__del__', self.value
d=Demo(1) # successfully create an object here
d=22 # new int object labeled 'd'; old 'd' goes out of scope
# '__del__ 1' is printed once a new name is put on old 'd'
# since the object is deleted with no references
现在尝试使用2
我们正在测试的值:
Demo(2)
Traceback (most recent call last):
File "Untitled 3.py", line 11, in <module>
Demo(2)
File "Untitled 3.py", line 5, in __init__
raise ValueError
ValueError
__del__ 2 # But note that `__del__` is still run.
使用值创建对象2
会引发ValueError
异常,并表明__del__
该对象仍在运行以清理对象。
请记住,如果在__init__
对象期间引发异常,则不会获得名称。(但是,它将被创建和销毁。由于__del__
与之配对__new__
仍然会被调用)
即,就像这样不会创建x
:
>>> x=1/0
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ZeroDivisionError: integer division or modulo by zero
>>> x
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'x' is not defined
潜在运动鞋:
>>> x='Old X'
>>> x=1/0
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ZeroDivisionError: division by zero
>>> x
'Old X'
如果您发现以下例外,也是如此__init__
:
try:
o=Demo(2)
except ValueError:
print o # name error -- 'o' never gets bound to the object...
# Worst still -- 'o' is its OLD value!
因此,请勿尝试引用不完整的对象o
-在您到达时,它已超出范围except
。该名称o
要么为空(即,NameError
如果您尝试使用它),要么为其旧值。
因此,总结一下(感谢Steve Jessop提出的“ 用户定义的异常”想法),您可以包装对象的创建并捕获异常。只需弄清楚如何对正在查看的操作系统错误做出适当的反应。
所以:
class ForbiddenTwoException(Exception):
pass
class Demo(object):
def __init__(self, value):
self.value=value
print 'trying to create with val:', value
if value==2:
raise ForbiddenTwoException
def __del__(self):
print '__del__', self.value
try:
o=Demo(2)
except ForbiddenTwoException:
print 'Doh! Cant create Demo with a "2"! Forbidden!!!'
# with your example - react to being unusable to create a directory...
印刷品:
trying to create with val: 2
Doh! Cant create Demo with a "2"! Forbidden!!!
__del__ 2
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句