基类的继承及其使用,以圆的内接正方形和外切正方形为例
时间: 2023-12-15 14:09:55 浏览: 23
好的,基类的继承是面向对象编程中的一个重要概念。它可以方便地通过定义一个基类来描述一类对象的特性和行为,然后通过继承来扩展这些特性和行为,从而实现代码的复用和扩展。
以圆的内接正方形和外切正方形为例,我们可以定义一个基类 Shape,用来描述所有图形对象的特性和行为。然后定义两个子类 Circle 和 Square,分别用来描述圆和正方形的特性和行为。最后,我们可以在子类中重写基类的方法,以实现特定的功能。
下面是示例代码:
```python
import math
class Shape:
def __init__(self, x, y):
self.x = x
self.y = y
def area(self):
pass
def circumference(self):
pass
class Circle(Shape):
def __init__(self, x, y, r):
super().__init__(x, y)
self.r = r
def area(self):
return math.pi * self.r ** 2
def circumference(self):
return 2 * math.pi * self.r
class Square(Shape):
def __init__(self, x, y, l):
super().__init__(x, y)
self.l = l
def area(self):
return self.l ** 2
def circumference(self):
return 4 * self.l
class InscribedSquare(Square):
def __init__(self, x, y, r):
super().__init__(x, y, 2 * r)
def area(self):
return self.l ** 2 / 2
def circumference(self):
return self.l * 4
class CircumscribedSquare(Square):
def __init__(self, x, y, r):
super().__init__(x, y, 2 * r * math.sqrt(2))
def area(self):
return self.l ** 2 / 2
def circumference(self):
return self.l * 4
```
在这个示例中,我们定义了一个 Shape 基类,它包含了所有图形对象的通用属性和方法。Circle 和 Square 两个子类继承了 Shape 基类,并重写了其中的 area 和 circumference 方法,以实现特定的功能。
另外,我们还定义了两个子类 InscribedSquare 和 CircumscribedSquare,用来描述圆的内接正方形和外接正方形。这两个子类同样继承了 Square 基类,并重写了其中的 area 和 circumference 方法,以实现特定的功能。
通过这种方式,我们可以方便地扩展和复用代码,并且使代码更加清晰和易于维护。