You need to enable JavaScript to run this app. Python循环同时取列表两相邻值触发AttributeError如何解决
优惠活动
大模型
产品
解决方案
定价
更多

Python循环同时取列表两相邻值触发AttributeError如何解决

问题修复方案

错误根源

你代码的报错核心出在Lot类的__getLines方法的遍历逻辑错误:

  • 直接遍历lstpoints拿到的每个i是Point类实例,执行i+1时会触发你重载的__add__方法,此时传入的第二个参数是整数1,Line类初始化时尝试读取整数的eastings属性自然失败,触发AttributeError。
  • 你之前尝试用i[0]/i[1]索引报错,是因为Point类没有实现__getitem__方法,这个修改方向本身不符合逻辑。
  • 额外还有两个隐藏问题:距离列表lst_dist全程没有写入数据,后续还把变量名错写为lst_dis,会触发NameError;Line继承Point、Lot继承Line的逻辑完全不合理,二者不存在父子类从属关系。

修复后的完整代码

import math

class Point:
    '''Class that creates points. Attributes: Eastings and Northings'''
    def __init__(self,x,y):
        self.eastings = x
        self.northings = y
    def getCoords(self):
        self.coords = (self.eastings,self.northings)
        return self.coords
    def setCoords(self,other_x,other_y):
        self.eastings = float(other_x)
        self.northings = float(other_y)
    def __str__(self):
        return f"{self.eastings},{self.northings}"
    def __add__(self,new_point):
        return Line(self,new_point)

class Line: # 移除不必要的Point继承
    '''Class that creates line object based on two points'''
    def __init__(self,start,end):
        self.start = start
        self.end = end
        self.latitude = self.end.eastings - self.start.eastings
        self.departure = self.end.northings - self.start.northings
        self.distance = math.sqrt((self.latitude)**2 + (self.departure)**2)
        self.azimuth = math.degrees(math.atan2(self.departure,self.latitude))
    def __getitem__(self,index):
        if index == 0:
            ans = self.start
        elif index == 1:
            ans = self.end
        else:
            print("invalid index")
        return ans

class Lot: # 移除不必要的Line继承
    def __init__(self,name,lstpoints):
        self.name = name
        self.corners = self.__setCorners(lstpoints)
        self.lines = self.__getLines(lstpoints)
        self.left = None
        self.right = None
    def __setCorners(self,lstpoints):
        dct = {}
        for k,val in enumerate(lstpoints):
            new = {f"C{k+1}":val}
            dct.update(new)
        return dct
    def __getLines(self,lstpoints):
        lst_lines = []
        lst_dist = []
        # 修正遍历逻辑,按索引取相邻点计算距离
        for k in range(len(lstpoints)-1):
            line_name = f"C{k+1}-C{k+2}"
            lst_lines.append(line_name)
            current_p = lstpoints[k]
            next_p = lstpoints[k+1]
            dist = Line(current_p, next_p).distance
            lst_dist.append(dist)
        # 修正变量名错误
        dct_lines = dict(zip(lst_lines,lst_dist))
        return dct_lines

# 测试代码
a = Point(0,0)
b = Point(1,1)
c = Point(1,0.5)
lot = Lot("A1",[a,b,c])
print(lot.lines) # 输出 {'C1-C2': 1.4142135623730951, 'C2-C3': 0.5}

内容的提问来源于stack exchange,提问作者rilke-nz

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.21 09:06:07