用法:
class functools.singledispatchmethod(func)将方法转换为 single-dispatch 泛型函数。
要定义泛型方法,请使用
@singledispatchmethod装饰器对其进行装饰。使用@singledispatchmethod定义函数时,请注意调度发生在第一个非self或非cls参数的类型上:class Negator: @singledispatchmethod def neg(self, arg): raise NotImplementedError("Cannot negate a") @neg.register def _(self, arg: int): return -arg @neg.register def _(self, arg: bool): return not arg@singledispatchmethod支持与其他装饰器嵌套,例如@classmethod。请注意,要允许dispatcher.register,singledispatchmethod必须是outer most装饰器。这是Negator类,其中neg方法绑定到类,而不是类的实例:class Negator: @singledispatchmethod @classmethod def neg(cls, arg): raise NotImplementedError("Cannot negate a") @neg.register @classmethod def _(cls, arg: int): return -arg @neg.register @classmethod def _(cls, arg: bool): return not arg相同的模式可用于其他类似的装饰器:
@staticmethod、@abstractmethod等。3.8 版中的新函数。
相关用法
- Python functools.singledispatch用法及代码示例
- Python functools.wraps用法及代码示例
- Python functools.partial用法及代码示例
- Python functools.partialmethod用法及代码示例
- Python functools.cache用法及代码示例
- Python functools.lru_cache用法及代码示例
- Python functools.reduce用法及代码示例
- Python functools.cached_property用法及代码示例
- Python functools.total_ordering用法及代码示例
- Python functools.wraps()用法及代码示例
- Python dict fromkeys()用法及代码示例
- Python frexp()用法及代码示例
- Python float转exponential用法及代码示例
- Python calendar firstweekday()用法及代码示例
- Python fsum()用法及代码示例
- Python float.is_integer用法及代码示例
- Python format()用法及代码示例
- Python calendar formatmonth()用法及代码示例
- Python filecmp.cmpfiles()用法及代码示例
注:本文由纯净天空筛选整理自python.org大神的英文原创作品 functools.singledispatchmethod。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。
