简体   繁体   English

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

[英]generating exception classes via decorators in python

While coding, I have to do this frequently; 在编码时,我必须经常这样做。

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

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

It'd be nice to be able to have my Exception classes via a decorator call, since all those dummy classes all inherited from Exception have nothing unique but name. 可以通过装饰器调用来获得Exception类,因为所有这些继承自Exception的虚拟类都没有唯一的名称。 The following would be great for instance; 例如,以下内容将非常有用;

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

Since there's no way to make MyClassException present until the decorator is called it'd give me syntax name error no matter what. 由于在调用装饰器之前,无法使MyClassException出现,因此无论如何它都会给我 语法 名称错误。 Is there a way to do this in python in any similar way? 有没有办法以类似的方式在python中做到这一点?

Here's one possibility. 这是一种可能性。 Note that the exception class will be a member of the decorated class, it is not at global scope. 请注意,异常类将是修饰类的成员,它不在全局范围内。

# 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