2 回答

TA貢獻(xiàn)1797條經(jīng)驗(yàn) 獲得超4個(gè)贊
尚不清楚如果不執(zhí)行以下操作,您如何期望FooBar存在?
def bad_function():
ExceptionClass = type( "FooBar", (Exception,),
{ "__init__": lambda self, msg: Exception.__init__(self, msg) })
globals()['FooBar'] = ExceptionClass
raise ExceptionClass("ExceptionClass")

TA貢獻(xiàn)1804條經(jīng)驗(yàn) 獲得超3個(gè)贊
您在函數(shù)內(nèi)部創(chuàng)建了該類,因此該類在模塊的全局命名空間中不作為名稱存在。實(shí)際上,它除了在bad_function執(zhí)行時(shí)根本不存在。失敗的原因相同:
# file1.py
def good_function():
x = 2
# file2.py
import file1
print file1.x
您的異常類只是內(nèi)部的局部變量bad_function。
添加回答
舉報(bào)