在Python中,没有像Java那样的直接方法重载机制,但可以通过几种方式模拟方法重载:
使用`if-elif-else`结构
def process_data(data):if isinstance(data, int):print("处理整数:", data * 2)elif isinstance(data, str):print("处理字符串:", data.upper())else:print("未知类型的数据:", data)
使用`functools.singledispatch`装饰器 (Python 3.8及以上版本支持):from functools import singledispatch@singledispatchdef fun(arg):print(arg)@fun.registerdef _(arg: int):print(f'arg is int: {arg}')@fun.registerdef _(arg: list):print(f'arg is list: {arg}')@fun.registerdef _(arg: str):print(f'arg is str: {arg}')fun([1, 2, 3])fun(1)fun('str')

from functools import singledispatch@singledispatchdef fun(arg):print(arg)@fun.registerdef _(arg: int):print(f'arg is int: {arg}')@fun.registerdef _(arg: list):print(f'arg is list: {arg}')@fun.registerdef _(arg: str):print(f'arg is str: {arg}')fun([1, 2, 3])fun(1)fun('str')
使用魔法方法(例如重载运算符):
class CustomSequence:def __init__(self, items=None):self.items = items or []def __add__(self, other):if not isinstance(other, CustomSequence):raise TypeError('Unsupported operand type(s)')return CustomSequence(self.items + other.items)seq1 = CustomSequence([1, 2, 3])seq2 = CustomSequence([4, 5, 6])combined_seq = seq1 + seq2[1:] 注意这里使用了切片来避免重复添加第一个元素
使用`inspect`模块
import inspectclass MultiMethod:def __init__(self, name):self._methods = {}self.__name__ = namedef register(self, meth):sig = inspect.signature(meth)types = []for name, parm in sig.parameters.items():if name == 'self':continueparm.annotationif parm.annotation is inspect.Parameter.empty:raise TypeError(f'参数 {name} 必须是有注解')if not isinstance(parm.annotation, type):raise TypeError(f'参数 {name} 的注解必须是类型')types.append(parm.annotation)self._methods[tuple(types)] = methdef __call__(self, *args, kwargs):for types, meth in self._methods.items():if all(isinstance(arg, t) for arg, t in zip(args, types)):return meth(*args, kwargs)raise TypeError('没有匹配的方法')
以上是Python中实现方法重载的几种方式。每种方法都有其适用场景,选择哪一种取决于具体的需求和偏好
