2017-09-14 10 views
-2
def pass_thru(func_to_decorate): 
    def new_func(*args, **kwargs): #1 
     print("Function has been decorated. Congratulations.") 
     # Do whatever else you want here 
     return func_to_decorate(*args, **kwargs) #2 
    return new_func 


def print_args(*args): 
    for arg in args: 
     print(arg) 


a = pass_thru(print_args) 
a(1,2,3) 

>> Function has been decorated. Congratulations. 
1 
2 
3 

나는 함수 선언이므로 *args이 # 1에서 사용된다는 것을 알고 있습니다. 하지만 함수 선언이 아닐지라도 # 2에 *args을 써야하는 이유는 무엇입니까? 함수 선언에 사용데코레이터에서`* args`가 필요한 이유는 무엇입니까?

+1

당신은 args의 튜플에 위치 인수를 번들링 한 다음 래핑 된 함수를 호출 할 때 별도의 인수로 다시 분리합니다. – jonrsharpe

답변

1

는 터플에 위치 인수를 설정 *args :

함수 호출에 사용
def foo(a, *args): 
    pass 
foo(1, 2, 3) # a = 1, args = (2, 3) 

, *args가 위치 인수로 튜플 확장 :

def bar(a, b, c): 
    pass 
args = (2, 3) 
foo(1, *args) # a = 1, b = 2, c = 3 

이 두 대향 프로세스이며 그래서 그것들을 조합하면 데코 레이팅 된 함수에 임의의 수의 인수를 전달할 수 있습니다.

@pass_thru 
def foo(a, b): 
    pass 
@pass_thru 
def bar(a, b, c): 
    pass 

foo(1, 2)  # -> args = (1, 2) -> a = 1, b = 2 
bar(1, 2, 3) # -> args = (1, 2, 3) -> a = 1, b = 2, c = 3