当方法重载在 Python 中不起作用时?

Patricia Arquette
发布: 2024-10-23 00:01:03
原创
472 人浏览过

When Method Overloading Doesn't Work in Python?

Python 中的方法重载

在 Python 中,方法重载是定义多个具有相同名称但不同参数的方法的能力。但是,这可能会导致一些意外的行为。

示例 1:

<code class="python">class A:
    def stackoverflow(self):    
        print ('first method')
    def stackoverflow(self, i):
        print ('second method', i)</code>
登录后复制

如果您使用参数调用该方法,则会调用第二个方法:

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

但是如果你不带参数调用它,Python会抛出一个错误:

<code class="python">ob=A()
ob.stackoverflow()
# Output: TypeError: stackoverflow() takes exactly 2 arguments (1 given)</code>
登录后复制

这是因为Python认为第一个方法没有参数,没有默认参数.

解决方案:

要解决此问题,您可以使用默认参数值:

<code class="python">class A:
    def stackoverflow(self, i='some_default_value'):
        print('only method')</code>
登录后复制

现在,两个调用都可以工作:

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

单次调度的高级重载

Python 3.4 引入了单次调度通用函数,它允许您为不同的参数类型定义特定的行为:

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

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

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

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

这允许您使用不同的参数类型调用 f​​un 并获得适当的行为:

<code class="python">fun(42)
# Output: Strength in numbers, eh? 42
fun([1, 2, 3])
# Output: Enumerate this:
# 0 1
# 1 2
# 2 3</code>
登录后复制

以上是当方法重载在 Python 中不起作用时?的详细内容。更多信息请关注PHP中文网其他相关文章!

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