不将嵌套类视为异常

时间:2018-01-03 18:25:48

标签: python-3.x inner-classes

以下代码表示无法找到MyError:

   class Test:
       class MyError(ValueError):
           pass

       def bad(self):
           raise MyError

       def myfunc(self):
           try:
               self.bad()
           except MyError as me:
               print(me)


   tt = Test()
   tt.myfunc()

当我运行它时,我得到了这个:

 Traceback (most recent call last):
   File "testcase.py", line 16, in <module>
     tt.myfunc()
   File "testcase.py", line 11, in myfunc
     except MyError as me:
 NameError: name 'MyError' is not defined

我在引用嵌套类时缺少什么?

1 个答案:

答案 0 :(得分:0)

原来我需要完全限定类的路径Test.MyError

 class Test:
     class MyError(ValueError):
         pass

     def bad(self):
         raise Test.MyError

     def myfunc(self):
         try:
             self.bad()
         except Test.MyError as me:
             print(me)


 tt = Test()
 tt.myfunc()