用法:
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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。