用python 定义一个抽象基类Shape,Shape不需要编写数据成员和方法: class Shape(object): pass 在Shape类上派生出子类Rectangle和Circle,并在Rectangle类上派生出子类Square。三者都有获取周长和面积的方法getCircumference()和getArea()。 编写程序生成三种形状的对象,并打印输出周长和面积。
时间: 2023-06-09 12:04:55 浏览: 278
好的,以下是Python代码:
```
from abc import ABC, abstractmethod
class Shape(ABC):
@abstractmethod
def getCircumference(self):
pass
@abstractmethod
def getArea(self):
pass
class Rectangle(Shape):
def __init__(self, length, width):
self.length = length
self.width = width
def getCircumference(self):
return 2 * (self.length + self.width)
def getArea(self):
return self.length * self.width
class Circle(Shape):
def __init__(self, radius):
self.radius = radius
def getCircumference(self):
return 2 * 3.1415926 * self.radius
def getArea(self):
return 3.1415926 * self.radius ** 2
class Square(Rectangle):
def __init__(self, side):
super().__init__(side, side)
rectangle = Rectangle(5, 10)
circle = Circle(7)
square = Square(4)
print("Rectangle circumference:", rectangle.getCircumference())
print("Rectangle area:", rectangle.getArea())
print("Circle circumference:", circle.getCircumference())
print("Circle area:", circle.getArea())
print("Square circumference:", square.getCircumference())
print("Square area:", square.getArea())
```
这个程序定义了一个抽象基类Shape,然后在这个基类上派生了两个子类Rectangle和Circle,又在Rectangle类上派生了一个子类Square。这三个类都拥有获取周长和面积的方法getCircumference()和getArea()。
代码中,我们分别生成了一个Rectangle、Circle和Square对象,然后打印输出这些对象的周长和面积。
阅读全文