如何把共同代码放到基类里,举例
时间: 2024-04-14 20:30:04 浏览: 18
假设我们有一个基类 `Shape`,其中包含了共同的代码,然后我们创建两个子类 `Rectangle` 和 `Circle` 来继承基类并使用其中的共同代码。以下是一个示例:
```python
class Shape:
def __init__(self, color):
self.color = color
def area(self):
pass
def perimeter(self):
pass
def display(self):
print(f"This shape is {self.color}.")
class Rectangle(Shape):
def __init__(self, color, width, height):
super().__init__(color)
self.width = width
self.height = height
def area(self):
return self.width * self.height
def perimeter(self):
return 2 * (self.width + self.height)
class Circle(Shape):
def __init__(self, color, radius):
super().__init__(color)
self.radius = radius
def area(self):
return 3.14 * self.radius**2
def perimeter(self):
return 2 * 3.14 * self.radius
```
在上述示例中,`Shape` 是基类,包含了共同的代码和一个抽象方法 `area()` 和 `perimeter()`。子类 `Rectangle` 和 `Circle` 继承了基类 `Shape`,并实现了自己的特定方法和属性。
在主文件中,我们可以创建一个矩形对象和一个圆形对象,并调用它们的共同代码:
```python
rectangle = Rectangle("red", 5, 10)
rectangle.display() # 输出:This shape is red.
print(rectangle.area()) # 输出:50
print(rectangle.perimeter()) # 输出:30
circle = Circle("blue", 7)
circle.display() # 输出:This shape is blue.
print(circle.area()) # 输出:153.86
print(circle.perimeter()) # 输出:43.96
```
通过将共同的代码放在基类中,我们可以在子类中直接调用基类的方法 `display()`,并根据需要重写或扩展其他方法。这样可以提高代码的重用性和可维护性。