当方法重载在 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("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>
这允许您使用不同的参数类型调用 fun 并获得适当的行为:
<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中文网其他相关文章!

热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

Video Face Swap
使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

记事本++7.3.1
好用且免费的代码编辑器

SublimeText3汉化版
中文版,非常好用

禅工作室 13.0.1
功能强大的PHP集成开发环境

Dreamweaver CS6
视觉化网页开发工具

SublimeText3 Mac版
神级代码编辑软件(SublimeText3)

使用FiddlerEverywhere进行中间人读取时如何避免被检测到当你使用FiddlerEverywhere...

如何在10小时内教计算机小白编程基础?如果你只有10个小时来教计算机小白一些编程知识,你会选择教些什么�...

攻克Investing.com的反爬虫策略许多人尝试爬取Investing.com(https://cn.investing.com/news/latest-news)的新闻数据时,常常�...

Python3.6环境下加载pickle文件报错:ModuleNotFoundError:Nomodulenamed...

使用Scapy爬虫时管道文件无法写入的原因探讨在学习和使用Scapy爬虫进行数据持久化存储时,可能会遇到管道文�...
