当我尝试重新定义一个枚举时,出现错误。
我的代码如下:
from enum import Enum
class FooEnum(Enum):
try:
foo = 3/0
except Exception as my_exception_instance:
print('An error occurred:', my_exception_instance)
foo=0
目标是让
3/0
引发异常,然后重新定义foo
。然而,当我按原样运行时,会显示打印消息,但会抛出另一个错误,这对我来说没有意义。以下是输出和堆栈跟踪:An error occurred: division by zero
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-10-489d2391f28b> in <module>
1 from enum import Enum
2
----> 3 class FooEnum(Enum):
4 try:
5 foo = 3/0
<ipython-input-10-489d2391f28b> in FooEnum()
6 except Exception as my_exception_instance:
7 print('An error occurred:', my_exception_instance)
----> 8 foo=0
/usr/lib/python3.6/enum.py in __setitem__(self, key, value)
90 elif key in self._member_names:
91 # descriptor overwriting an enum?
---> 92 raise TypeError('Attempted to reuse key: %r' % key)
93 elif not _is_descriptor(value):
94 if key in self:
TypeError: Attempted to reuse key: 'my_exception_instance'
想要解决这个错误,唯一的方法就是在捕捉异常时不使用它:
from enum import Enum
class FooEnum(Enum):
try:
foo = 3/0
except:
print('An error occurred')
foo=0
然后它只会输出:发生了一个错误
我正在使用Python 3.6.9版本
编辑 下面的代码更接近我的用例:
import tensorflow as tf
from enum import Enum
class VisualModels(Enum):
try:
MobileNet = tf.keras.applications.MobileNetV2
except Exception as e:
print(f'MobileNetV2 Not found, using MobileNet instead. Error: {e}.')
MobileNet = tf.keras.applications.MobileNet
# more models are defined similarly