Python调用Picture对象getFrameColour方法触发AttributeError求助
问题解决:AttributeError: 'Picture' object has no attribute 'getFrameColour'
错误原因
你的Picture类定义中,getDescription、getWidth、getHeight、getFrameColour以及SetDescription这些方法没有缩进在类的范围内,它们被定义成了独立于类的普通函数,因此Picture实例调用这些方法时会提示找不到属性。
修复后的完整代码
class Picture: def __init__(self, DescriptionP, WidthP, HeightP, FrameColourP): self.__Description = DescriptionP # string self.__Width = WidthP # integer self.__Height = HeightP # integer self.__FrameColour = FrameColourP # string def getDescription(self): return self.__Description # 返回对应属性给用户 def getWidth(self): return self.__Width # 规则:仅在需要时使用参数,否则只使用self和类属性 def getHeight(self): return self.__Height def getFrameColour(self): return self.__FrameColour # 使用类定义时指定的参数,假设用户已传入有效值 def SetDescription(self, DescriptionP): self.__Description = DescriptionP # 初始化空数组,替代多次写入None的方式 PictureArray = [] # 由于类需要参数,先初始化100个空属性的Picture对象 for i in range(100): PictureArray.append(Picture("", 0, 0, "")) def ReadData(PictureArray): # 路径加r前缀避免转义字符解析错误 filename = r"C:\Users\ayush\Downloads\Pictures.txt" NumberPicturesInArray = 0 try: file = open(filename, "r") # 读取第一行描述并转为小写 Description = (file.readline()).strip().lower() while Description != "": # 读取尺寸并转为整数,边框颜色转为小写 Width = int((file.readline()).strip()) Height = int((file.readline()).strip()) Frame = ((file.readline()).strip()).lower() # 替换数组中对应位置的空对象 PictureArray[NumberPicturesInArray] = Picture( Description, Width, Height, Frame) # 读取下一行描述,准备循环 Description = ((file.readline()).strip()).lower() NumberPicturesInArray += 1 # 原代码循环结束后追加空描述对象,如不需要可注释 # PictureArray.append(Picture(DescriptionP=Description, # WidthP=Width, HeightP=Height, FrameColourP=Frame)) file.close() except IOError: print("Could not find file!") return NumberPicturesInArray, PictureArray # 调用函数并接收返回值 NumberPicturesInArray, PictureArray = ReadData(PictureArray) # 接收用户输入并统一转为小写/整数 FrameColour = input("Input the Frame colour ").lower() MaxWidth = int(input("Input the Maximum Width ")) MaxHeight = int(input("Input the Maximum Height ")) print("Matches Frames shown") # 遍历有效数据范围 for Z in range(0, NumberPicturesInArray): if PictureArray[Z].getFrameColour() == FrameColour: if PictureArray[Z].getWidth() <= MaxWidth: if PictureArray[Z].getHeight() <= MaxHeight: print(PictureArray[Z].getDescription(), " ", str(PictureArray[Z].getWidth()), " ", str( PictureArray[Z].getHeight()), " ", PictureArray[Z].getFrameColour())
额外优化说明
- 文件路径添加
r前缀,避免反斜杠被解析为转义字符导致路径错误; - 注释掉了循环结束后追加空描述图片的代码(如业务需要可取消注释);
- 确保所有类方法的缩进与
__init__方法一致,保证它们属于Picture类的成员方法。
内容的提问来源于stack exchange,提问作者Ayush Rai
相关产品推荐
相关产品推荐

