2012-09-06 3 views
9

가능한 중복 :
Understanding Python decorators파이썬 장식 자만 통사론 설탕?

나는 그들이 단지 문법 설탕 것을 파이썬 장식을 사용하여 내가 내 첫 인상에 뭘 이해에서 아주 새로운 오전.

좀 더 복잡한 용도로 더 많이 사용합니까?

+2

사용 예제는 여기에 있습니다. http://stackoverflow.com/questions/739654/understanding-python-decorators#answer-1594484 –

+0

감사합니다. 이 게시물을 닫거나 삭제하는 방법을 모르겠다. 누군가가 이것을 할 수 있다면 좋을 것입니다. – coredump

+0

그리고 작은 자습서를 통해 정확히 무엇인지 확인할 수 있습니다. https://www.codementor.io/python/tutorial/introduction-to-decorators – Sheena

답변

10

네, 그것은 문법 설탕입니다. 모든 것이 코드 없이도 구현 될 수 있습니다. 하지만 좀 더 간결한 코드를 작성하는 데 도움이됩니다.

예 :

from functools import wraps 

def requires_foo(func): 
    @wraps(func) 
    def wrapped(self, *args, **kwargs): 
     if not hasattr(self, 'foo') or not self.foo is True: 
      raise Exception('You must have foo and be True!!') 
     return func(self, *args, **kwargs) 
    return wrapped 

def requires_bar(func): 
    @wraps(func) 
    def wrapped(self, *args, **kwargs): 
     if not hasattr(self, 'bar') or not self.bar is True: 
      raise Exception('You must have bar and be True!!') 
     return func(self, *args, **kwargs) 
    return wrapped 

class FooBar(object): 

    @requires_foo     # Make sure the requirement is met. 
    def do_something_to_foo(self): 
     pass 

우리는 또한 체인/서로의 상단에 장식 스택 수 있습니다.

class FooBar(object): 
    @requires_bar 
    @requires_foo     # You can chain as many decorators as you want 
    def do_something_to_foo_and_bar(self): 
     pass 

좋아, 우리는 서로의 위에 많은 장식 자들로 끝날 수 있었다.

알아요! 나는 다른 데코레이터를 적용하는 데코레이터를 쓸 것이다.

그래서 우리는이 작업을 수행 할 수 있습니다 :

def enforce(requirements): 
    def wrapper(func): 
     @wraps(func) 
     def wrapped(self, *args, **kwargs): 
      return func(self, *args, **kwargs) 
     while requirements: 
      func = requirements.pop()(func) 
     return wrapped 
    return wrapper 

class FooBar(object): 
    @enforce([reguires_foo, requires_bar]) 
    def do_something_to_foo_and_bar(self): 
     pass 

이 그냥 노는 작은 샘플입니다.

2

나는 정말

예를 들어 명시 적 코드 동네 짱은, 장고이 login_required 장식있을 수 있기 때문에 장식 구문 같은 : https://docs.djangoproject.com/en/dev/topics/auth/#django.contrib.auth.decorators.login_required

함수/보려면 @login_required 동작을 주입하려면, 당신은 모든 해 데코레이터를 부착하는 경우 (if : ... else : ... 어디에서나 식을 제어)

PEP를 읽으십시오.

http://www.python.org/dev/peps/pep-0318/

이 만들어진 언어 결정에 losta 역사를 가지고, 왜