Python 接口继承与实现:几何图形示例
- 定义了两个子接口 'ICircle' 和 'IRectangle' 继承自父接口 'IGeometry'。
class IGeometry:
pass
class ICircle(IGeometry):
pass
class IRectangle(IGeometry):
pass
- 定义了两个类 'Circle' 和 'Rectangle' 来实现上述接口。
class Circle(ICircle):
def __init__(self, radius):
self.radius = radius
class Rectangle(IRectangle):
def __init__(self, width, height):
self.width = width
self.height = height
- 编写示例程序演示接口和类的用法。
circle = Circle(5)
rectangle = Rectangle(10, 20)
print(isinstance(circle, ICircle)) # 输出: True
print(isinstance(rectangle, IRectangle)) # 输出: True
print(isinstance(rectangle, ICircle)) # 输出: False
- 下面是使用 UML 方式画出接口和类的关系图。
+------------+
| IGeometry |
+------------+
/_
|
+-------------+
| ICircle |
+-------------+
/ \
/ \
/ \
+------------+ +---------------+
| IRectangle | | Circle |
+------------+ +---------------+
\
\
\
+-----------+
| Rectangle |
+-----------+
请注意,由于当前环境不支持图形操作,因此无法生成精确的 UML 图。上述示意图仅用于概念演示。
原文地址: http://www.cveoy.top/t/topic/bnm1 著作权归作者所有。请勿转载和采集!