Python 可以实现方法重载吗?如何实现?

Mary-Kate Olsen
发布: 2024-10-22 23:56:29
原创
458 人浏览过

Can Python Implement Method Overloading and How?

Python 中的方法重载:详细说明

问题:

尝试使用以下代码实现方法重载:

<code class="python">class A:
    def stackoverflow(self):
        print('first method')

    def stackoverflow(self, i):
        print('second method', i)

ob = A()
ob.stackoverflow(2)  # Output: second method 2
ob.stackoverflow()  # Error: Takes exactly 2 arguments (1 given)</code>
登录后复制

解决方案:

与方法重写不同,Python 本身不支持方法重载。因此,有必要以不同的方式实现它:

<code class="python">class A:
    def stackoverflow(self, i='some_default_value'):
        print('only method')

ob = A()
ob.stackoverflow(2)  # Output: second method 2
ob.stackoverflow()  # Output: only method</code>
登录后复制

通过为 i 参数指定默认参数值,单个函数可以处理这两种情况。这种方法根据提供的参数数量有效地重载了函数。

进一步探索:

Python 3.4 使用 functools.singledispatch 装饰器引入了单调度泛型函数:

<code class="python">from functools import singledispatch

@singledispatch
def fun(arg, verbose=False):
    if verbose:
        print("Let me just say, ", end=" ")
    print(arg)

@fun.register(int)
def _(arg, verbose=False):
    if verbose:
        print("Strength in numbers, eh?", end=" ")
    print(arg)

@fun.register(list)
def _(arg, verbose=False):
    if verbose:
        print("Enumerate this:")
    for i, elem in enumerate(arg):
        print(i, elem)</code>
登录后复制

这提供了一种更明确的方式来定义不同参数类型的方法重载。

以上是Python 可以实现方法重载吗?如何实现?的详细内容。更多信息请关注PHP中文网其他相关文章!

来源:php
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
作者最新文章
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!