繁体   English   中英

通过python中的装饰器生成异常类

[英]generating exception classes via decorators in python

在编码时,我必须经常这样做。

class MyClassException(Exception):
    def __init__(self, _message):
        self.message = _message

class MyClass(object):
    def __init__(self, value):
        raise MyClassException("What's up?")

可以通过装饰器调用来获得Exception类,因为所有这些继承自Exception的虚拟类都没有唯一的名称。 例如,以下内容将非常有用;

 @generic_exception_class
 class MyClass(object):
    def __init__(self, value):
        raise MyClassException("What's up?")

由于在调用装饰器之前,无法使MyClassException出现,因此无论如何它都会给我 语法 名称错误。 有没有办法以类似的方式在python中做到这一点?

这是一种可能性。 请注意,异常类将是修饰类的成员,它不在全局范围内。

# The decorator
def class_with_exception(cls):
    def init(self, _message=''):
        self.message = _message
    excname = 'ClsException'
    excclass = type(excname, (Exception,), {'__init__': init})
    setattr(cls, excname, excclass)
    return cls

# example usage
@class_with_exception
class MyClass(object):
    def __init__(self):
        raise MyClass.ClsException('my message')

# raises and catches exception
try:
    MyClass()
except MyClass.ClsException:
    print 'catching exception'

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM