如何将元组多值作为函数单个参数传入?Python代码求助
修正后的代码实现
首先修复你的代码问题,让maths函数正确接收另一组点的元组,并使用元组索引完成运算:
class numbers(): def points(self, x: float, y: float): self.x = x self.y = y return self.x, self.y def maths(self, other_point: tuple[float, float]): # 将自身的坐标转为元组 current_point = (self.x, self.y) # 直接通过元组索引执行运算 return current_point[0] - other_point[0] + current_point[1] - other_point[1] # 实例化并设置坐标 num1 = numbers() num2 = numbers() num1.points(4, 10) num2.points(5, 11) # 传入num1返回的坐标元组进行计算 result = num2.maths(num1.points()) print(result) # 输出:2
原代码的问题说明
- 参数传递错误:你调用
num2.maths(num1.points)时,传递的是num1的points方法对象,而非该方法返回的元组。需要改为调用方法获取元组:num1.points()。 args处理错误:原maths函数中foobar2 = args[0], args[1]会导致索引越界——因为传入单个元组时,args是((4,10),),args[1]不存在。直接接收元组参数会更清晰。
可选优化方案
如果希望maths同时支持传入元组或两个独立坐标值,可以调整为:
def maths(self, *args): # 根据参数格式解析出另一组点的元组 if len(args) == 1 and isinstance(args[0], tuple): other_point = args[0] elif len(args) == 2: other_point = args else: raise ValueError("请传入一个坐标元组或两个数值") current_point = (self.x, self.y) return current_point[0] - other_point[0] + current_point[1] - other_point[1]
这样既可以用num2.maths(num1.points()),也可以用num2.maths(4, 10)来调用。
内容的提问来源于stack exchange,提问作者user16109723
相关产品推荐
相关产品推荐

