热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

WritingFunctionswithSameNameandDifferentParameters

WritingFunctionswithSameNameandDifferentParameters-Ivebeenwonderinghowtowritefunctionsandm

I've been wondering how to write functions and methods with the same name but different parameters, as if we had "overloaded" them. According to wiki, this is called multiple dispatching because in Python it happens in run time but not compile time.

Fortunately, there has been a discussion on Stack Overflow: python-function-overload. People have showed various ways to solve this problem. For example, here's a third-party library we can use: https://github.com/coady/mult...

I've also come up with a solution to this problem by slightly changing the code of David Beazley, the author of Python Cookbook, who used function annotations to implement multiple dispatchings. He has kindly put his code here: https://github.com/dabeaz/pyt...

And here's my code. The main idea is to use a dictionary to map the name of arguments (instead of the annotation) to the corresponding functions. I stored the arguments' names in a frozen set so that argument list [a, b, c] and [c, b, a] mean to call the same function.

class MultiMethod:
    
    def __init__(self, name):
        self._methods = {}
        self.__name__ = name
    
    def register(self, meth):
        sig = inspect.signature(meth)
        arg_names = []
        for name, parm in sig.parameters.items():
            if name == 'self':
                continue
            if parm.default is not inspect.Parameter.empty:
                self._methods[frozenset(arg_names)] = meth  
            
            # we can make var_names a frozen set 
            # so that f(a, b, c) and f(c, b, a) means the same thing
            arg_names.append(name)
            
        self._methods[frozenset(arg_names)] = meth
    
    def __call__(self, *args, **kwargs):
        """
        call a method based on name of the arguments
        *args is used to hold the "self" argument of the caller, which is 
        an instance of a class 
        """
        arg_names = frozenset(kwargs.keys())
        meth = self._methods.get(arg_names, None)
        if meth:
            return meth(*args, **kwargs)
        else:
            raise TypeError(f"No matching method for arguments {arg_names}")
    def __get__(self, instance, cls):
        if instance is not None:
        # MethodType bounds a method to an instance
            return types.MethodType(self, instance)  
        else:
            return self

This is enough to solve the problem raised in the discussion:

And we can use the rest of the code proivded by David to create a class whose methods can be overloaded:

All that said, in Python we can just use functions with different names to handle most of the situations. AoP also suggests us use overloading only when the functions perform the same task but have arguments of different types. So all of these multiple dispatching stuff I write here is just for summary, practice and fun :D


推荐阅读
  • 在Android开发中,使用Picasso库可以实现对网络图片的等比例缩放。本文介绍了使用Picasso库进行图片缩放的方法,并提供了具体的代码实现。通过获取图片的宽高,计算目标宽度和高度,并创建新图实现等比例缩放。 ... [详细]
  • 微软头条实习生分享深度学习自学指南
    本文介绍了一位微软头条实习生自学深度学习的经验分享,包括学习资源推荐、重要基础知识的学习要点等。作者强调了学好Python和数学基础的重要性,并提供了一些建议。 ... [详细]
  • 使用在线工具jsonschema2pojo根据json生成java对象
    本文介绍了使用在线工具jsonschema2pojo根据json生成java对象的方法。通过该工具,用户只需将json字符串复制到输入框中,即可自动将其转换成java对象。该工具还能解析列表式的json数据,并将嵌套在内层的对象也解析出来。本文以请求github的api为例,展示了使用该工具的步骤和效果。 ... [详细]
  • CF:3D City Model(小思维)问题解析和代码实现
    本文通过解析CF:3D City Model问题,介绍了问题的背景和要求,并给出了相应的代码实现。该问题涉及到在一个矩形的网格上建造城市的情景,每个网格单元可以作为建筑的基础,建筑由多个立方体叠加而成。文章详细讲解了问题的解决思路,并给出了相应的代码实现供读者参考。 ... [详细]
  • FeatureRequestIsyourfeaturerequestrelatedtoaproblem?Please ... [详细]
  • 标题: ... [详细]
  • SpringBoot整合SpringSecurity+JWT实现单点登录
    SpringBoot整合SpringSecurity+JWT实现单点登录,Go语言社区,Golang程序员人脉社 ... [详细]
  • 使用圣杯布局模式实现网站首页的内容布局
    本文介绍了使用圣杯布局模式实现网站首页的内容布局的方法,包括HTML部分代码和实例。同时还提供了公司新闻、最新产品、关于我们、联系我们等页面的布局示例。商品展示区包括了车里子和农家生态土鸡蛋等产品的价格信息。 ... [详细]
  • 本文整理了Java中java.lang.NoSuchMethodError.getMessage()方法的一些代码示例,展示了NoSuchMethodErr ... [详细]
  • 本文整理了Java中com.evernote.android.job.JobRequest.getTransientExtras()方法的一些代码示例,展示了 ... [详细]
  • 本文介绍了利用ARMA模型对平稳非白噪声序列进行建模的步骤及代码实现。首先对观察值序列进行样本自相关系数和样本偏自相关系数的计算,然后根据这些系数的性质选择适当的ARMA模型进行拟合,并估计模型中的位置参数。接着进行模型的有效性检验,如果不通过则重新选择模型再拟合,如果通过则进行模型优化。最后利用拟合模型预测序列的未来走势。文章还介绍了绘制时序图、平稳性检验、白噪声检验、确定ARMA阶数和预测未来走势的代码实现。 ... [详细]
  • 本文整理了Java中org.apache.solr.common.SolrDocument.setField()方法的一些代码示例,展示了SolrDocum ... [详细]
  • 如何使用PLEX播放组播、抓取信号源以及设置路由器
    本文介绍了如何使用PLEX播放组播、抓取信号源以及设置路由器。通过使用xTeve软件和M3U源,用户可以在PLEX上实现直播功能,并且可以自动匹配EPG信息和定时录制节目。同时,本文还提供了从华为itv盒子提取组播地址的方法以及如何在ASUS固件路由器上设置IPTV。在使用PLEX之前,建议先使用VLC测试是否可以正常播放UDPXY转发的iptv流。最后,本文还介绍了docker版xTeve的设置方法。 ... [详细]
  • 深度学习中的Vision Transformer (ViT)详解
    本文详细介绍了深度学习中的Vision Transformer (ViT)方法。首先介绍了相关工作和ViT的基本原理,包括图像块嵌入、可学习的嵌入、位置嵌入和Transformer编码器等。接着讨论了ViT的张量维度变化、归纳偏置与混合架构、微调及更高分辨率等方面。最后给出了实验结果和相关代码的链接。本文的研究表明,对于CV任务,直接应用纯Transformer架构于图像块序列是可行的,无需依赖于卷积网络。 ... [详细]
  • 本文概述了JNI的原理以及常用方法。JNI提供了一种Java字节码调用C/C++的解决方案,但引用类型不能直接在Native层使用,需要进行类型转化。多维数组(包括二维数组)都是引用类型,需要使用jobjectArray类型来存取其值。此外,由于Java支持函数重载,根据函数名无法找到对应的JNI函数,因此介绍了JNI函数签名信息的解决方案。 ... [详细]
author-avatar
童月圆524
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有