以下是 Python 的实现:

def add(a, b):
    if isinstance(a, int) and isinstance(b, int):
        return a + b
    elif isinstance(a, str) and isinstance(b, str):
        return a + b
    elif isinstance(a, list) and isinstance(b, list):
        return a + b
    elif isinstance(a, tuple) and isinstance(b, tuple):
        return a + b
    else:
        raise TypeError('Unsupported type(s) for addition')

# 示例
print(add(1, 2))  # 输出 3
print(add('hello', 'world'))  # 输出 'helloworld'
print(add([1, 2], [3, 4]))  # 输出 [1, 2, 3, 4]
print(add((1, 2), (3, 4)))  # 输出 (1, 2, 3, 4)

以上实现中,我们使用了 Python 的 isinstance 函数来判断变量的类型,然后根据类型进行相应的操作。如果传入的类型不支持加法,则抛出 TypeError 异常。

Python 实现通用加法函数,支持数字、字符串、列表和元组

原文地址: https://www.cveoy.top/t/topic/nmnL 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录