파이썬 장식기 사용법 분석

3921 단어
본문의 실례는 파이톤 장식기의 사용법을 설명하였다.여러분에게 참고하도록 공유하겠습니다. 구체적으로는 다음과 같습니다.
종류를 장식기로 쓰다
예제 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()

파이썬에 관한 더 많은 내용은 본 사이트의 주제를 보실 수 있습니다.,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,.
본고에서 서술한 것이 여러분의 파이톤 프로그램 설계에 도움이 되었으면 합니다.

좋은 웹페이지 즐겨찾기