파 이 썬 장식 기 용법 분석
클래스 를 장식 기로 하 다
예시 1
초기 코드:
class bol(object):
def __init__(self, func):
self.func = func
def __call__(self):
return "<b>{}</b>".format(self.func())
class ita(object):
def __init__(self, func):
self.func = func
def __call__(self):
return "<i>{}</i>".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 "<{tag}>{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()
더 많은 파 이 썬 관련 내용 은 본 사이트 의 주 제 를 볼 수 있 습 니 다.Python 데이터 구조 및 알고리즘 튜 토리 얼,Python Socket 프로 그래 밍 기술 총화,Python 함수 사용 기법 총화,Python 문자열 조작 기법 집합과Python 입문 및 진급 고전 튜 토리 얼본 논문 에서 말 한 것 이 여러분 의 Python 프로 그래 밍 에 도움 이 되 기 를 바 랍 니 다.
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
Python의 None과 NULL의 차이점 상세 정보그래서 대상 = 속성 + 방법 (사실 방법도 하나의 속성, 데이터 속성과 구별되는 호출 가능한 속성 같은 속성과 방법을 가진 대상을 클래스, 즉 Classl로 분류할 수 있다.클래스는 하나의 청사진과 같아서 하나의 ...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.