def obj_sum(obj1, obj2): if type(obj1) == type(obj2): if isinstance(obj1, (int, float, complex)): return obj1 + obj2 elif isinstance(obj1, str): return obj1 + obj2 elif isinstance(obj1, (list, tuple)): return obj1 + obj2 else: return 'Error: objects are not of the same type'

print(obj_sum(3, 4)) print(obj_sum('hello', 'world')) print(obj_sum([1, 2, 3], [4, 5, 6])) print(obj_sum((1, 2, 3), (4, 5, 6))) print(obj_sum(3, 'hello')) # Error: objects are not of the same type

Python 函数实现求两个对象之和 (数值、字符串、列表、元组)

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

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