You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何解决计算点到原点距离时出现的AttributeError

问题解决:AttributeError: 'tuple' object has no attribute 'x'

错误原因

你的distance_of_points方法设计为接收**Points类的实例**作为参数,它会访问参数的x和y属性。但在distance_from_origin方法里,你传入的是(0,0)这个元组,元组没有x、y属性,因此触发了AttributeError。

解决办法

方法一:传入Points类实例(最直接)

修改distance_from_origin方法,把(0,0)换成Points(0,0),让参数符合方法的预期类型:

class Points:
  def __init__(self,x,y):
    self.x = x
    self.y = y
  def distance_of_points(self,other):
    d = ((self.x-other.x)**2+(self.y-other.y)**2)**0.5
    return d
  def distance_from_origin(self):
    # 替换为Points实例
    return self.distance_of_points(Points(0,0))

p1 = Points(3,4)
print(p1.distance_from_origin())  # 输出5.0

方法二:让distance_of_points兼容元组/列表(更灵活)

修改distance_of_points方法,判断参数类型,如果是元组/列表就直接取值,如果是Points实例就访问属性:

class Points:
  def __init__(self,x,y):
    self.x = x
    self.y = y
  def distance_of_points(self,other):
    # 判断参数类型,兼容元组/列表和Points实例
    if isinstance(other, (tuple, list)):
      ox, oy = other
    else:
      ox, oy = other.x, other.y
    d = ((self.x - ox)**2 + (self.y - oy)**2)**0.5
    return d
  def distance_from_origin(self):
    return self.distance_of_points((0,0))

p1 = Points(3,4)
print(p1.distance_from_origin())  # 输出5.0
# 同时也支持和其他Points实例计算距离
p2 = Points(0,0)
print(p1.distance_of_points(p2))  # 输出5.0

内容的提问来源于stack exchange,提问作者Saurabh Dubey

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.24 06:10:54