파이썬 장식기 사용법 분석
종류를 장식기로 쓰다
예제 1
최초 코드:
class bol(object):
def __init__(self, func):
self.func = func
def __call__(self):
return "{}".format(self.func())
class ita(object):
def __init__(self, func):
self.func = func
def __call__(self):
return "{}".format(self.func())
@bol
@ita
def sayhi():
return 'hi'
개선 1:
class sty(object):
def __init__(self, tag):
self.tag = tag
def __call__(self, f):
def wraper():
return "{res}{tag}>".format(res=f(), tag=self.tag)
return wraper
@sty('b')
@sty('i')
def sayhi():
return 'hi'
개선 2:
class sty(object):
def __init__(self, *tags):
self.tags = tags
def __call__(self, f):
def wraper():
n = len(self.tags)
return "{0}{1}{2}".format((''*n).format(*self.tags), f(), ('{}>'*n).format(*reversed(self.tags)))
return wraper
@sty('b', 'i')
def sayhi():
return 'hi'
print(sayhi())
개선 3:
class sty(object):
def __init__(self, *tags):
self.tags = tags
def __call__(self, f):
def wraper(*args, **kwargs):
n = len(self.tags)
return "{0}{1}{2}".format((''*n).format(*self.tags), f(*args, **kwargs), ('{}>'*n).format(*reversed(self.tags)))
return wraper
@sty('b', 'i')
def say(word='Hi'):
return word
print(say())
print(say('Hello'))
예제 2
최초 코드:
import threading
import time
class DecoratorClass(object):
def __init__(self):
self.thread = None
def __call__(self, func, *args, **kwargs):
def wrapped_func(*args, **kwargs):
curr_thread = threading.currentThread().getName()
self.thread = curr_thread
print('
thread name before running func:', self.thread)
ret_val = func()
print('
thread name after running func:', self.thread)
return ret_val
return wrapped_func
@DecoratorClass()
def decorated_with_class():
print('running decorated w class')
time.sleep(1)
return
threads = []
for i in range(5):
t = threading.Thread(target=decorated_with_class)
threads.append(t)
t.setDaemon(True) #
t.start()
개선:프로세스 잠금
import threading
import time
class DecoratorClass(object):
def __init__(self):
self.thread = None
self.lock = threading.Lock()
def __call__(self, func, *args, **kwargs):
def wrapped_func(*args, **kwargs):
self.lock.acquire()
curr_thread = threading.currentThread().getName()
self.thread = curr_thread
print('thread name before running func:', self.thread)
ret_val = func()
print('
thread name after running func:', self.thread)
self.lock.release()
return ret_val
return wrapped_func
@DecoratorClass()
def decorated_with_class():
print('Let me sleep 1 second...')
time.sleep(1)
return
threads = []
for i in range(5):
t = threading.Thread(target=decorated_with_class)
threads.append(t)
t.start()
파이썬에 관한 더 많은 내용은 본 사이트의 주제를 보실 수 있습니다.,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,.
본고에서 서술한 것이 여러분의 파이톤 프로그램 설계에 도움이 되었으면 합니다.
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
다양한 언어의 JSONJSON은 Javascript 표기법을 사용하여 데이터 구조를 레이아웃하는 데이터 형식입니다. 그러나 Javascript가 코드에서 이러한 구조를 나타낼 수 있는 유일한 언어는 아닙니다. 저는 일반적으로 '객체'{}...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.