我在看Python: Exception in the separate module works wrong它使用多用途 GnuLibError 类来“代替”各种不同的错误。每个子错误都有自己的 ID 号和错误格式字符串。
我认为最好将其编写为 Exception 类的层次结构,并着手这样做:
class GNULibError(Exception):
sub_exceptions = 0 # patched with dict of subclasses once subclasses are created
err_num = 0
err_format = None
def __new__(cls, *args):
print("new {}".format(cls)) # DEBUG
if len(args) and args[0] in GNULibError.sub_exceptions:
print(" factory -> {} {}".format(GNULibError.sub_exceptions[args[0]], args[1:])) # DEBUG
return super(GNULibError, cls).__new__(GNULibError.sub_exceptions[args[0]], *(args[1:]))
else:
print(" plain {} {}".format(cls, args)) # DEBUG
return super(GNULibError, cls).__new__(cls, *args)
def __init__(self, *args):
cls = type(self)
print("init {} {}".format(cls, args)) # DEBUG
self.args = args
if cls.err_format is None:
self.message = str(args)
else:
self.message = "[GNU Error {}] ".format(cls.err_num) + cls.err_format.format(*args)
def __str__(self):
return self.message
def __repr__(self):
return '{}{}'.format(type(self).__name__, self.args)
class GNULibError_Directory(GNULibError):
err_num = 1
err_format = "destination directory does not exist: {}"
class GNULibError_Config(GNULibError):
err_num = 2
err_format = "configure file does not exist: {}"
class GNULibError_Module(GNULibError):
err_num = 3
err_format = "selected module does not exist: {}"
class GNULibError_Cache(GNULibError):
err_num = 4
err_format = "{} is expected to contain gl_M4_BASE({})"
class GNULibError_Sourcebase(GNULibError):
err_num = 5
err_format = "missing sourcebase argument: {}"
class GNULibError_Docbase(GNULibError):
err_num = 6
err_format = "missing docbase argument: {}"
class GNULibError_Testbase(GNULibError):
err_num = 7
err_format = "missing testsbase argument: {}"
class GNULibError_Libname(GNULibError):
err_num = 8
err_format = "missing libname argument: {}"
# patch master class with subclass reference
# (TO DO: auto-detect all available subclasses instead of hardcoding them)
GNULibError.sub_exceptions = {
1: GNULibError_Directory,
2: GNULibError_Config,
3: GNULibError_Module,
4: GNULibError_Cache,
5: GNULibError_Sourcebase,
6: GNULibError_Docbase,
7: GNULibError_Testbase,
8: GNULibError_Libname
}
这以 GNULibError 作为工厂类开始 - 如果您使用属于可识别子类的错误号调用它,它会返回一个属于该子类的对象,否则它会将自身作为默认错误类型返回。
基于此代码,以下内容应该完全等效(但不是):
e = GNULibError(3, 'missing.lib')
f = GNULibError_Module('missing.lib')
print e # -> '[GNU Error 3] selected module does not exist: 3'
print f # -> '[GNU Error 3] selected module does not exist: missing.lib'
我添加了一些战略打印语句,错误似乎在GNULibError.__new__
:
>>> e = GNULibError(3, 'missing.lib')
new <class '__main__.GNULibError'>
factory -> <class '__main__.GNULibError_Module'> ('missing.lib',) # good...
init <class '__main__.GNULibError_Module'> (3, 'missing.lib') # NO!
^
why?
我称子类构造函数为subclass.__new__(*args[1:])
- 这应该删除 3,子类类型 ID - 但它__init__
仍然得到 3!如何修剪传递给的参数列表subclass.__init__
?