2013-06-18 83 views
0

临时异常类是在python脚本中动态使用'type'来定义的,该脚本用作模块。当此类的实例在导入脚本中被捕获时,它无法识别该类。 下面的代码片段动态定义的类在导入模块中不可见python

# the throwing module, defines dynamically 
def bad_function(): 
    ExceptionClass = type("FooBar", (Exception,), 
     { "__init__": lambda self, msg: Exception.__init__(self, msg) }) 
    raise ExceptionClass("ExceptionClass") 

的使用代码

import libt0 

try: 
    libt0.bad_function() 
#except libt0.FooBar as e: 
#print e 
except Exception as e: 
    print e 
    print e.__class__ 

能不能解释为什么libt0.FooBase是不是这个脚本可见?最后一行的观察员输出。

回答

2

目前尚不清楚,你怎么指望FooBar的,而不做这样的事情

def bad_function(): 
    ExceptionClass = type("FooBar", (Exception,), 
     { "__init__": lambda self, msg: Exception.__init__(self, msg) }) 
    globals()['FooBar'] = ExceptionClass 
    raise ExceptionClass("ExceptionClass") 
+0

由于存在,这个工程。我必须承认,我的蟒蛇知识很浅薄。我在Python中学到的所有东西都是语法和一些生存库。我主要是C/C++的人。帮助真的很感激@gnibbler。 – user2496012

2

您在函数内部创建了类,所以它不作为模块的全局名称空间中的名称存在。实际上,除了bad_function正在执行之外,它根本不存在。这是同样的原因失败:

# file1.py 
def good_function(): 
    x = 2 

# file2.py 
import file1 
print file1.x 

你的异常类只是内部bad_function一个局部变量。