# Python本身不直接支持函数重载,但可以通过一些技巧实现类似的效果。以下是几种实现方法:
# 方法1:使用默认参数
def func(a, b=None):
if b is None:
print(f"单个参数: {a}")
else:
print(f"两个参数: {a}, {b}")
# 调用示例
func(1) # 输出: 单个参数: 1
func(1, 2) # 输出: 两个参数: 1, 2
# 方法2:使用*args和**kwargs
def overloaded_function(*args, **kwargs):
if len(args) == 1 and len(kwargs) == 0:
print(f"单个位置参数: {args[0]}")
elif len(args) == 2 and len(kwargs) == 0:
print(f"两个位置参数: {args[0]}, {args[1]}")
elif len(args) == 0 and len(kwargs) == 1:
key = list(kwargs.keys())[0]
value = kwargs[key]
print(f"单个关键字参数: {key}={value}")
else:
print("其他情况")
# 调用示例
overloaded_function(1) # 输出: 单个位置参数: 1
overloaded_function(1, 2) # 输出: 两个位置参数: 1, 2
overloaded_function(name="Alice") # 输出: 单个关键字参数: name=Alice
# 方法3:使用装饰器实现类中的方法重载
from functools import singledispatchmethod
class Calculator:
@singledispatchmethod
def add(self, a, b):
raise NotImplementedError("Unsupported type")
@add.register(int)
def _(self, a: int, b: int):
print(f"整数相加: {a + b}")
@add.register(str)
def _(self, a: str, b: str):
print(f"字符串拼接: {a + b}")
# 调用示例
calc = Calculator()
calc.add(1, 2) # 输出: 整数相加: 3
calc.add("Hello, ", "World!") # 输出: 字符串拼接: Hello, World!
以上代码展示了三种实现Python函数重载的方法,并附有调用示例和解释说明。
上一篇:python var
下一篇:python 调用js
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站