处理__init__中的异常

Abhishek Chanda:

__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
检查以查看目录是否存在后,向函数添加了调用

dawg:

在中引发异常是完全可以的__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] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章

来自分类Dev

__init__方法中的异常处理

来自分类Python

Python:在__init__中引发异常是不好的形式吗?

来自分类Dev

如何处理python __init__中缺少的args?

来自分类Dev

__init__函数中处理多个args的优雅方法

来自分类Dev

__init__中的UnboundLocalError

来自分类Dev

如何在高速公路Python ApplicationSession .__ init__中引发异常?

来自分类Dev

在 __init__ 中设置属性

来自分类Dev

在 Flask 中从 __init__ 导入

来自分类Dev

Python:类中的 __init__

来自分类Dev

在 Python 中的 __init__() 中添加方法

来自分类Dev

Python中的__init__自动运行方法

来自分类Dev

在Python中从__init__调用setter

来自分类Dev

在类方法中访问__init__ vars

来自分类Dev

python类的属性不在__init__中

来自分类Dev

在__init__中更改类属性

来自分类Python

如何防止__init__在目录中运行?

来自分类Python

Python中的__new__和__init__

来自分类Dev

类或__init__构造函数中的docstring?

来自分类Dev

类__init__中的TypeVar类型提示

来自分类Python

__init__和Python中的参数

来自分类Dev

在ModelForm的__init__中访问请求

来自分类Dev

在__init__方法中传递参数

来自分类Dev

在Python中从__init__调用setter

来自分类Dev

__init__方法中的属性设置器?

来自分类Dev

__init__中的Python输入注释

来自分类Dev

Python / Kivy中的__init__参数

来自分类Dev

__init__方法中的变量范围?

来自分类Dev

Scrapy __init__ arg中的ValueError

来自分类Dev

__init__括号中的内容是什么?