@functools.singleDispatchMethod的后台端口到python 2.7-3.7。
singledispatchmethod的Python项目详细描述
来自@functools.singledispatchmethoddecorator[1]的后台端口 Python3.8到Python2.7-3.7。这些代码只有大约30行,但是 何必为仿制意大利面而烦恼呢?
$ pip install singledispatchmethod
decorator将方法转换为单个分派[2]泛型 函数[3]。注意,由于分派发生在 第一个非self或非cls参数,必须创建函数 相应地:
fromsingledispatchmethodimportsingledispatchmethodclassNegator:@singledispatchmethoddefneg(self,arg):raiseNotImplementedError("Cannot negate a")@neg.registerdef_(self,arg:int):return-arg@neg.registerdef_(self,arg:bool):returnnotarg
@singledispatchmethod支持与其他装饰器(如 @classmethod。但是,为了公开dispatcher.register, @singledispatchmethod必须是最外面的装饰符。这是 Negator类,neg方法是类绑定的:
fromsingledispatchmethodimportsingledispatchmethodclassNegator:@singledispatchmethod@classmethoddefneg(cls,arg):raiseNotImplementedError("Cannot negate a")@neg.register@classmethoddef_(cls,arg:int):return-arg@neg.register@classmethoddef_(cls,arg:bool):returnnotarg
相同的模式可以用于其他类似的装饰器,例如 @staticmethod或@abstractmethod。请注意,因为 @singledispatchmethoddecorator基于 @functools.singledispatch,支持类型注释 dispatcher.register仅在python 3.7之后。
[1] | https://docs.python.org/3.8/library/functools.html#functools.singledispatchmethod |
[2] | https://docs.python.org/3.8/glossary.html#term-single-dispatch |
[3] | https://docs.python.org/3.8/glossary.html#term-generic-function |