# Python 重载示例
# 在 Python 中,严格意义上并不支持像 C++ 或 Java 那样的方法重载,
# 但可以通过其他方式实现类似的效果。以下是几种常见的实现方法:
# 方法1:使用默认参数
class Calculator:
def add(self, a, b=0, c=0):
return a + b + c
# 使用示例
calc = Calculator()
print(calc.add(1)) # 输出: 1
print(calc.add(1, 2)) # 输出: 3
print(calc.add(1, 2, 3)) # 输出: 6
# 方法2:使用 *args 和 **kwargs
class MultiCalculator:
def add(self, *args):
return sum(args)
# 使用示例
multi_calc = MultiCalculator()
print(multi_calc.add(1)) # 输出: 1
print(multi_calc.add(1, 2)) # 输出: 3
print(multi_calc.add(1, 2, 3, 4)) # 输出: 10
# 方法3:使用 functools.singledispatch
from functools import singledispatchmethod
class TypeBasedCalculator:
@singledispatchmethod
def add(self, arg):
raise NotImplementedError("Unsupported type")
@add.register(int)
def _(self, a: int, b: int = 0):
return a + b
@add.register(list)
def _(self, a: list):
return sum(a)
# 使用示例
type_calc = TypeBasedCalculator()
print(type_calc.add(1, 2)) # 输出: 3
print(type_calc.add([1, 2, 3, 4])) # 输出: 10
和
kwargs`:允许函数接受任意数量的位置参数和关键字参数,从而实现灵活的参数传递。functools.singledispatchmethod
:根据传入参数的类型选择不同的处理逻辑,类似于多态。这些方法都可以在一定程度上实现类似方法重载的效果。
上一篇:python的print
下一篇:python正则替换
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站