2011-03-18 85 views
1

编码时,我必须经常这样做;通过python中的装饰器生成异常类

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

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

这将会是很高兴能够通过装饰呼吁有我的异常类,因为所有这些虚拟类都继承自Exception有什么独一无二的,但名称。以下将是很好的例子;

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

既然没有办法让MyClassException目前,直至装饰被称为它会给我 语法 名称错误不管是什么。有没有办法在Python中以任何类似的方式做到这一点?

+0

只要实例化类,就会调用装饰器。问题在哪里? – 2011-03-18 05:33:10

+0

由MyClassException引起的语法错误未事先定义 – ocivelek 2011-03-18 05:34:00

+0

1)这将是一个名称错误,而不是语法错误。 2)直到实际调用'__init __()'之后,Python才会关心它不存在。 – 2011-03-18 05:35:06

回答

1

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

# 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' 
+0

看起来像一个可行的想法:)谢谢。如果我们没有看到更好的东西,我可以接受这个答复。 – ocivelek 2011-03-18 07:28:36