Skip to content

Instantly share code, notes, and snippets.

@geekKeen
Created August 23, 2017 09:39
Show Gist options
  • Save geekKeen/4ad00853f3178e9802a9d5c9228bc69b to your computer and use it in GitHub Desktop.
Save geekKeen/4ad00853f3178e9802a9d5c9228bc69b to your computer and use it in GitHub Desktop.
当遇到switch-case 时 处理的技巧, 符合开放封闭原则, 以functions 中singledispath 为例
from functions import singledispatch
@singledispatch
def my_func(args):
print('default myfunc({!r})'.format(arg))
@my_func.register(int)
def my_func(args):
print('myfunc_int({})'.format(arg))
@myfunc.register(list)
def myfunc_list(arg):
print('myfunc_list()')
for item in arg:
print(' {}'.format(item))
@geekKeen
Copy link
Author

  1. 首先在 dispatch 中维护一个字典,字典中存有 key: func
  2. 想 dispatch 中注册事件
  3. 当调用时,在字典中找出对应的 func

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment