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

Python代码出现AttributeError:金字塔面积计算第二种方法失效求助

问题分析与解决

你的代码运行area_2()时出现AttributeError,核心有两个错误:

1. Triangle类属性未初始化

RightPyramid多重继承了Square和Triangle,但你只在__init__中执行了Square的初始化逻辑,Triangle的__init__未被触发,导致调用tri_area()时找不到self.height,触发AttributeError。

正金字塔的侧面三角形高就是传入的slant_height,需要在RightPyramid的__init__中手动初始化Triangle的属性:

def __init__(self, base, slant_height) -> None:
    self.base = base
    self.slant_height = slant_height
    super().__init__(self.base)
    # 初始化Triangle的属性,height对应斜高
    Triangle.__init__(self, self.base, self.slant_height)

2. 误引用方法对象而非调用方法

area_2中base_area = super(Square, self).area未加括号,导致base_area是方法对象而非计算后的数值,后续无法与三角形面积相加引发错误。需要改为调用方法:

base_area = super(Square, self).area()

修正后的完整代码

class Rectangle:
    def __init__(self, length, width) -> None:
        self.length = length
        self.width = width

    def area(self) -> float:
        return self.length * self.width

    def perimeter(self) -> float:
        return 2 * self.length + 2 * self.width

class Square(Rectangle):
    def __init__(self, length) -> None:
        super(Square, self).__init__(length, length)

class Cube(Square):
    def surface_area(self) -> float:
        face_area = super(Square, self).area()
        return face_area * 6

    def volume(self) -> float:
        face_area = super(Square, self).area()
        return face_area * self.length

class Triangle:
    def __init__(self, base, height) -> None:
        self.base = base
        self.height = height

    def tri_area(self) -> float:
        return 0.5 * self.base * self.height

class RightPyramid(Square, Triangle):
    def __init__(self, base, slant_height) -> None:
        self.base = base
        self.slant_height = slant_height
        super().__init__(self.base)
        Triangle.__init__(self, self.base, self.slant_height)

    def area(self) -> float:
        base_area = super(Square, self).area()
        perimeter = super(Square, self).perimeter()
        return 0.5 * perimeter * self.slant_height + base_area

    def area_2(self) -> float:
        base_area = super(Square, self).area()
        triangle_area = super(Triangle, self).tri_area()
        return triangle_area * 4 + base_area

print(RightPyramid.__mro__) 
pyramid = RightPyramid(3, 6)
print(pyramid.area())
print(pyramid.area_2())

运行后两个方法都会返回正确结果:

(<class '__main__.RightPyramid'>, <class '__main__.Square'>, <class '__main__.Rectangle'>, <class '__main__.Triangle'>, <class 'object'>)
45.0
45.0

内容的提问来源于stack exchange,提问作者Ali Baghdadi

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 09:33:21