파 이 썬 장식 기 용법 분석

4510 단어 Python장식 기
이 글 의 실례 는 Python 장식 기의 용법 을 서술 하 였 다.여러분 께 참고 하도록 공유 하 겠 습 니 다.구체 적 으로 는 다음 과 같 습 니 다.
클래스 를 장식 기로 하 다
예시 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 프로 그래 밍 에 도움 이 되 기 를 바 랍 니 다.

좋은 웹페이지 즐겨찾기