2011-03-18 4 views
1

코딩하는 동안 자주해야합니다.파이썬의 장식자를 통해 예외 클래스 생성하기

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 선물을 할 수 없기 때문에. 비슷한 방식으로 파이썬에서이 작업을 수행 할 수있는 방법이 있습니까?

+0

데코레이터는 클래스가 인스턴스화되는 즉시 호출됩니다. 문제가 어디 있니? –

+0

미리 정의되지 않은 MyClassException에 의한 구문 오류 – ocivelek

+0

1) 구문 오류가 아닌 이름 오류입니다. 2) 파이썬은'__init __()'가 실제로 호출되기 전에는 존재하지 않는다는 것에 신경 쓰지 않습니다. –

답변

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

관련 문제