Python 传递函数的层次结构

Python Hierarchy passing a function

try: Polygon
except: from Polygon import Polygon

class Triangle(Polygon):

def __init__(self, width, height):

    sides = 3
    super().__init__(sides, width)

#        self.__side2 = s2
#        self.__side3 = s3
    self.__height = height

def get_height(self):
    """Returns height"""
    return self.__height    

def set_height(self, height):
    """Sets the height"""
    if height <= 0:
        raise ValueError('Height must be positive')
    self.__height = height
try: Triangle
except: from Triangle import Triangle, Polygon

child class

class IsocelesTriangle(Polygon):

def __init__(self, width, height):

#      sides = 3

    super().__init__ (width, height)

def get_area(self):
    """Gets the area of an isoceles triangle"""
    area = ((1/2) * (self.get_width()) * (self.get_height()))
    return area

def get_perimeter(self):
    """Returns the are of an isoceles triangle"""
    p = (2 * self.get_width()) + self.get_height()
    return p

所以我遇到一个问题,三角形 class 高于 IsocelesTriangle class,有一个多边形 class 更高,我从中得到宽度。然而,我已经尝试了几个小时才能将三角形的高度放入 IsocelesTriangle class 但它一直在抛出:

AttributeError: 'IsocelesTriangle' object has no attribute 'get_height'

任何线索将不胜感激。

您的 IsocelesTriangle 并未继承您的 Triangle class。相反,它继承自 Polygon。因此它不会看到 get_height 函数。