Created
January 20, 2018 09:04
-
-
Save nlpjoe/9ac744065248e0870bad11db8b69ce42 to your computer and use it in GitHub Desktop.
[python中两种利用singledispatch实现实例方法分发]#python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
### 基础的singledispatch装饰器只能实现静态方法 | |
from functools import singledispatch | |
class TestClass(object): | |
@singledispatch | |
def test_method(arg, verbose=False): | |
if verbose: | |
print("Let me just say,", end=" ") | |
print(arg) | |
@test_method.register(int) | |
def _(arg): | |
print("Strength in numbers, eh?", end=" ") | |
print(arg) | |
@test_method.register(list) | |
def _(arg): | |
print("Enumerate this:") | |
for i, elem in enumerate(arg): | |
print(i, elem) | |
if __name__ == '__main__': | |
TestClass.test_method(55555) | |
TestClass.test_method([33, 22, 11]) | |
------------------- | |
### singledispatch装饰器只能实现静态方法,因为装饰器返回的第一个参数在类中总是self | |
# def wrapper(*args, **kw): | |
# return dispatch(args[0].__class__)(*args, **kw) | |
# 第一种方法 | |
from functools import singledispatch, update_wrapper | |
def methdispatch(func): | |
dispatcher = singledispatch(func) | |
def wrapper(*args, **kw): | |
return dispatcher.dispatch(args[1].__class__)(*args, **kw) | |
wrapper.register = dispatcher.register | |
update_wrapper(wrapper, func) | |
return wrapper | |
class Patchwork(object): | |
def __init__(self, **kwargs): | |
for k, v in kwargs.items(): | |
setattr(self, k, v) | |
@methdispatch | |
def get(self, arg): | |
return getattr(self, arg, None) | |
@get.register(list) | |
def _(self, arg): | |
return [self.get(x) for x in arg] | |
# 第二种方法 | |
from functools import singledispatch | |
class TestClass(object): | |
def __init__(self): | |
self.test_method = singledispatch(self.test_method) | |
self.test_method.register(int, self._test_method_int) | |
self.test_method.register(list, self._test_method_list) | |
def test_method(self, arg, verbose=False): | |
if verbose: | |
print("Let me just say,", end=" ") | |
print(arg) | |
def _test_method_int(self, arg): | |
print("Strength in numbers, eh?", end=" ") | |
print(arg) | |
def _test_method_list(self, arg): | |
print("Enumerate this:") | |
for i, elem in enumerate(arg): | |
print(i, elem) | |
if __name__ == '__main__': | |
test = TestClass() | |
test.test_method(55555) | |
test.test_method([33, 22, 11]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment