首页 > 编程语言 >python singledispatch 使用简单说明

python singledispatch 使用简单说明

时间:2024-03-12 20:00:14浏览次数:22  
标签:return python int add singledispatch str 简单 print def

singledispatch 可以实现类似方法的范型能力,以下是使用的简单说明

方法

  • 参考代码
from functools import singledispatch
@singledispatch
def add(a,b):
    return f"default---{a}-{b}"
 
@add.register
def _(a:int,b:int)->int:
    return a + b
 
@add.register
def _(a:str,b:str)->str:
    return f"{a} {b}---str"
 
@add.register(float)
def _(a:float,b:float)->float:
    return a + b + 100
 
result = add(1,3)
result2 = add("dalong","demoapap")
result3 = add(0.1,0.2)
(a,b) = ((1,3),(3,4))
result4 = add(a,b)
print(result)
print(result2)
print(result3)
print(result4)

对于类的使用,注意需要python 3.8 以及以上

  • 参考代码
from functools import singledispatchmethod
 
class A:
    @singledispatchmethod
    def add(self,a,b):
        return f"default---{a}-{b}"
 
    @add.register
    def _(self,a:int,b:int)->int:
        return a + b + 100    
 
    @add.register
    def _(self,a:str,b:str)->str:
        return  f"{a} {b}---str"
 
a  = A()
result = a.add(1,3)
result2 = a.add("dalong","demoapap")
result3 = a.add(0.1,0.2)
print(result)
print(result2)
print(result3)
  • 低版本的处理
    提供一个新的包装方法
from functools import singledispatch, wraps
 
def singledispatchmethod(func):
    dispatcher = singledispatch(func)
 
    @wraps(func)
    def wrapper(*args, **kwargs):
        return dispatcher.dispatch(args[1].__class__)(*args, **kwargs)
 
    wrapper.register = dispatcher.register
    return wrapper
class A:
    @singledispatchmethod
    def add(self,a,b):
        return f"default---{a}-{b}"
 
    @add.register
    def _(self,a:int,b:int)->int:
        return a + b + 100    
 
    @add.register
    def _(self,a:str,b:str)->str:
        return  f"{a} {b}---str"
 
a  = A()
result = a.add(1,3)
result2 = a.add("dalong","demoapap")
result3 = a.add(0.1,0.2)
print(result)
print(result2)
print(result3)

说明

python 的singledispatch 比较有意思,对于开发是一个很不错的小技巧,比如dbt 中就使用了dispatch 的概念处理macro(没有使用python的singledispatch)实现比较方便的处理调用不同adapter 自己的macro 方法

参考资料

https://peps.python.org/pep-0443/

标签:return,python,int,add,singledispatch,str,简单,print,def
From: https://www.cnblogs.com/rongfengliang/p/18068703

相关文章

  • Python-使用openpyxl读取excel内容
    1.本篇文章目标将下面的excel中的寄存器表单读入并构建一个字典2.openpyxl的各种基本使用方法2.1打开工作簿wb=openpyxl.load_workbook('test_workbook.xlsx')2.2获取工作簿中工作表名字并得到工作表ws=wb[wb.sheetnames[0]]wb.sheetnames会返回一个列表,列表中......
  • Python基于微博的舆论分析,舆论情感分析可视化系统(V5.0),附源码
    博主介绍:✌程序员徐师兄、7年大厂程序员经历。全网粉丝12w+、csdn博客专家、掘金/华为云/阿里云/InfoQ等平台优质作者、专注于Java技术领域和毕业项目实战✌......
  • Python的特性——跟老吕学Python编程
    Python的特性——跟老吕学Python编程Python的特性1.Python易学易用2.Python是解释型语言3.Python是交互式的4.Python是一种多范式语言5.Python的标准库6.Python是开源的7.Python是跨平台的8.用于GUI应用程序的Python9.Python的数据库连接10.Python是可扩展的11.Python拥......
  • Python毕业设计 人工智能与大数据专业毕业设计(论文)选题题目
    目录前言毕设选题人工智能大数据选题迷茫选题的重要性更多选题指导最后 前言  ......
  • Python基础_多进程数据共享
    Python基础_多进程数据共享一、多进程数据共享二、使用multiprocessing.Manager对象三、使用multiprocessing.Value和multiprocessing.Array四、使用管道和队列五、使用共享内存六、注意事项一、多进程数据共享Python中,多进程之间的数据共享是一个复杂的主题,因为每个......
  • Android RecyclerView的使用(以实现一个简单的动态聊天界面为例)
    RecycleView可以实现动态列表的功能,毕竟在实际开发中大多数情况下不可能提前知道一个列表要塞进去多少东西。比如说QQ微信的聊天栏界面,可以抽象成一个RecycleView(或者一个ListView),没人说话时列表为空,你发一句话我发一句话,这列表就长起来了。再或者像是一些管理系统里,每一个物品......
  • python 递归比较两个文件夹
    以下importfilecmp,osdefcompare_folders(folder1,folder2):dcmp=filecmp.dircmp(folder1,folder2)fornameindcmp.left_only:print(f"{folder1}单独存在的文件:{name}")fornameindcmp.right_only:print(f"{folder......
  • Python函数每日一讲 - id()
    引言几天不见,今天我们来看看一个比较特别的函数id(),这个函数就是用来获取对象在内存中的唯一标识符的函数。语句概览id()函数是Python内置函数之一,用于获取对象在内存中的唯一标识符。其语法格式如下:id(object)其中,object参数是要获取标识符的对象。函数实例例1:获取整数......
  • macOS 下使用 pyenv 安装 python 2.n.p 报错,ERROR: The Python zlib extension was no
    TL;DR执行brewinstallzlib安装zlib之后,根据安装信息提示将一下三行变量exportLDFLAGS="-L/opt/homebrew/opt/zlib/lib"exportCPPFLAGS="-I/opt/homebrew/opt/zlib/include"exportPKG_CONFIG_PATH="/opt/homebrew/opt/zlib/lib/pkgconfig"加入到~/.zsh......
  • python得scrapy提取数据 xpath注意事项
    在提取器过滤数据这个地方被坑了很久,确实有点坑,有点难以理解,多注意下就可以了。frommultiprocessingimportallow_connection_picklingfromscrapy.spidersimportSpiderfrom..itemsimportCnblogshaha01ItemclasscnblogSpider(Spider):name="cnblogsHAHA01"#定......