1.簡單註冊表
funcs = []
def register(func):
funcs.append(func)
return func
@register
def a():
return 3
@register
def b():
return 5
result = [func() for func in funcs]
# 訪問結果
# [3,5]
2.接收rabbit包,根據包字段不同註冊不同函數調用
class MqModel:
def __init__(self):
self.registryCenter = {}
def msg_dispacher(self,body, message):
"""
數據分發
:param body:
:param message:
:return:
"""
try:
jdata = json.loads(body)
head = jdata['head']
except ValueError:
print("Not support non-json msg",body)
message.ack()
return
finally:
if 'op' not in head:
message.ack()
print("special msg ERROR", body)
return
if head['op'] in self.registryCenter:
for func in self.registryCenter[head['op']]:
func(jdata)
else:
print("jdata['op'] not in self.registryCenter:")
def registryConsumer(msgtype):
def wrapper(func):
if msgtype in mqModel.registryCenter:
mqModel.registryCenter[msgtype].append(func)
else:
mqModel.registryCenter[msgtype]=[func]
return wrapper
@registryConsumer('web-phone-update')
def receive_statusMsg(body):
"""
註冊收報回調
:param body:
:param message:
:return:
"""
print('web-phone-update')
print(body)
3.使用裝飾器在函數前後添加一行Log
def log(function):
def wrapper(*args,**kwargs):
print('before func')
res = function(*args,**kwargs)
print('after func')
return res
return wrapper
@log
def func(str):
print('execute func %s' % str)
4.使用帶參數的裝飾器
import functools
def log(text):
def decorate(function):
@functools.wraps(function)
def wrapper(*args, **kwargs):
print('%s before func' % text)
res = function(*args, **kwargs)
print('%s after func' % text)
return res
return wrapper
return decorate
@log('param')
def func(str):
print('execute func %s' % str)
5.裝飾器實現的單例模式
def singleton(cls, *args, **kwargs):
instance = {}
def _singleton():
if cls not in instance:
instance[cls] = cls(*args, **kwargs)
return instance[cls]
return _singleton
@singleton
class test_singleton(object):
name = None
def __init__(self):
self.sum = 0
def add(self, name):
self.name = name
if __name__ == '__main__':
cls1 = test_singleton()
cls1.add('cls1')
cls2 = test_singleton()
cls2.add('cls2')
cls3 = test_singleton()
cls3.add('cls3')
print(cls1)
print(cls2)
print(cls3)
print(cls1.name)
print(cls2.name)
print(cls3.name)