Python Decorator(4)
デコレーションの関数の前後に機能を追加することで、関数のテクニック を簡単に利用できます.
アクセサリーを使う複数の関数は、同じ機能を1つの@Decoratorの に簡単に追加できます.関数パラメータの有効性チェック 複数のデコーダ クラスでレコーダ を使用する.デコーダ に使用する.
アクセサリーを使う
# decorator 함수 정의
def outer_func(function):
def inner_func():
print('decoration added')
function()
return inner_func
def log_func():
print('logging')
decorated_func = outer_func(log_func)
decorated_func()
""" 위 코드를 데코레이터 적용해보면 다음과 같이 바꿀 수 있음. """
# decorator 함수 정의
def outer_func(function):
def inner_func():
print('decoration added')
function()
return inner_func
@outer_func
def log_func():
print('logging')
log_func()
def type_checker(func):
def check(digit1, digit2):
if (type(digit1) != int) or (type(digit2) != int):
return print("정수가 아닙니다")
func(digit1,digit2)
return check
""" 위 코드를 보면, 넘겨 받는 인자가 정수가 아닐 때 데코레이터에서 유효성 체크로 걸러낼 수 있다 """
@type_checker
def calc(digit1, digit2):
print(digit1 * digit2)
def decorater(fuc):
def inner_func():
print("데코레이터")
fuc()
return inner_func
def decorater1(fuc):
def inner_func():
print("데코레이터1")
fuc()
return inner_func
@decorater
@decorater1
def hello():
print("헬로")
hello()
""" 데코레이터
데코레이터1
헬로 """
def hi_tag(func):
def inner_func(self, *arg, **kwargs):
return '<h1>{0}</h1>'.format(func(self, *arg, **kwargs))
return inner_func
""" 클래스 내에서 사용할 데코레이터는 self 를 첫번째 인자로 넘겨준다. """
class Person:
def __init__(self, first_name, last_name):
self.first_name = first_name
self.last_name = last_name
@hi_tag
def get_name(self):
return self.first_name + self.last_name
a = Person("태경", "정")
print(a.get_name())
パラメータをdef decorater(a,b): # 데코레이터로 넘겨받을 인자
def outter_func(func): # 데코레이터 밑에 넘겨받을 함수
def inner_func(args):
return a + func(args) + b
return inner_func
return outter_func
@decorater('<i>', '</i>')
def test(string):
return string
print(test('무야홍~'))
Reference
この問題について(Python Decorator(4)), 我々は、より多くの情報をここで見つけました https://velog.io/@tkjung/파이썬-데코레이터4テキストは自由に共有またはコピーできます。ただし、このドキュメントのURLは参考URLとして残しておいてください。
Collection and Share based on the CC Protocol